How can I inject html after the [x]th widget inside a Sidebar?

I can’t provide you with any code since I not really know where to start.

I like to add some programmatically created widgets (or just html) after the 1st Widget inside my sidebar. Right now I have it that I have to include this widgets before all others, that was pretty easy of course.

Related posts

2 comments

  1. If I’m understanding you correctly, a dirty way to achieve this would be to use 2 sidebar areas on the page: an upper and lower. Call the upper, then include your code, then call the lower.

    Other ways might be to create your own widget that pulls in the appropriate data at runtime, but you haven’t explained the “programmatically created” part of your requirement.

  2. Edit: Forgot – add this code to your functions.php

    function nb_widget_number( $params ) {
        $widget_id = $params[0]['id'];
        $widget_array = wp_get_sidebars_widgets();
        $widget_count = count( $widget_array[$widget_id] );
    
            // set widget number to array if not set already    
        if( !$nb_widget_num )
            $nb_widget_num = array();
    
            // if no widgets, return params
        if( !isset( $widget_array[$widget_id] ) || !is_array( $widget_array[$widget_id]) )
            return $params;
    
            // if widget number set, add 1, if not, set to 1             
        isset( $nb_widget_num[$widget_id] ) ? $nb_widget_num[$widget_id] ++ : $nb_widget_num[$widget_id] = 1;
    
        // now you can do anything with that count you want. in this case, place something after the nth widget (1st for this example)
            if( $nb_widget_num[$widget_id] == 1 )
                $params[0]['after_widget'] = 'SOME CODE';
    
            return $params;
    }
    

    Then you just need to add the filter to let wordpress know to use this function:

    add_filter( 'dynamic_sidebar_params', 'nb_widget_number');
    

    In addition to adding code after the widget, you can use this to add code, modify classes (such as first/last), or really change any feature about the widgets $params.

Comments are closed.