Insert custom content before widget title/after widget opening tag

I am trying to target a widget with a specific class, and place something directly after the opening tag or before the widget title.

This:

Read More
<widget>
<h3>Title</h3>
<p>Some content goes here...</p>
</widget>

Becomes:

<widget>
<!-- Custom content or element goes here -->
<h3>Title</h3>
<p>Some content goes here...</p>
</widget>

I can’t quite hook into it, I do not want to use css, this needs to be added with widget logic in order to be user-friendly.

Related posts

1 comment

  1. You can use the dynamic_sidebar_params filter:

    add_filter( 'dynamic_sidebar_params', 
        function( $params )
        {
           // target a sidebar id:
           if( isset( $params[0]['id'] ) && 'sidebar-1' === $params[0]['id']
           {    
               // target a widget name:
               if( isset( $params[0]['widget_name'] ) && 'Text' === $params[0]['widget_name'] )
               {
                   // target a widget id:
                   if( isset( $params[0]['widget_id'] ) && 'text-8' === $params[0]['widget_id'] )
                   {
                       // Append text to existing 'before widget' markup code:
                       if( isset( $params[0]['before_widget'] ) )
                       { 
                           $params[0]['before_widget'] .= '<!-- Custom content -->';
                       }
                   }
                }
             }
             return $params;
        } 
    );
    

    where the widget names are for example: Text, Categories, Calendar, … .

    You can then modify it to your needs, for example the 'sidebar-1', 'Text' and 'text-8' parts.

Comments are closed.