0

On the index page of my website. I want to display a widget in the third position. I am calling the widget through "the_widget( 'Widget Name' );" code. Now the problem is, since it doesn't return anything.

It will display the widget in the first position in my loop. Is there any way, I can store the widget content in a variable and display on third position. Or any other work around may be.

Thanks.

  • Widgets are displayed in the order you store them in the admin panel. If you put the widget in the third position in Appearance -> Widgets in the admin panel, it shows up in the third position on the front-end. – engelen Mar 27 '16 at 18:43
  • I am not using side bar or any such thing for widget display. I am calling them directly through the_widget() function at home page's posts loop. – Rookie Mar 27 '16 at 18:46
1

You can check what iteration you're on inside the main loop with $wp_query->current_post

while( have_posts() ){
    the_post();

    the_title();

    // count starts at zero, so after 1 will be after 2nd post
    if( 1 == $wp_query->current_post ){
        the_widget( 'WP_Widget_Recent_Posts' );
    }

}

Edit

Regarding your comment about capturing widget output, you can try PHP output buffering:

ob_start();
the_widget( 'WP_Widget_Recent_Posts' );
$widget_output = ob_get_clean();
  • I have tried this. Actually the loop is storing all the values in a variable and then returning it. I am hoping if I could do this $out .= the_widget( 'Name' ); – Rookie Mar 27 '16 at 19:21
  • see edit above. – Milo Mar 27 '16 at 20:04
  • Thanks for this. I am reading more about ob_start() and clean(). – Rookie Mar 27 '16 at 20:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.