I am using a Twenty Eleven Child Theme and I’m trying to insert sidebars (well, widget areas) between the posts showing on my home page. (My website if you think it’s helpful to have a look, although I don’t think it’s necessary?)
I have registered the sidebars in functions.php as follows
register_sidebar( array( 'name' => __( 'Post widget 1', 'yourtheme' ), 'id' => 'sidebar-7', 'description' => __( 'Widget area between 1st and 2nd post', 'yourtheme' ), 'before_widget' => '<aside id="%1$s" class="widget %2$s">', 'after_widget' => "</aside>", 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', ) );
There are two more (Post widget 2 and Post widget 3) which I made in the same way.
These work in that they are visible and functional in Appearance>Widgets.
Obviously however I need to tell index.php where to put my sidebars. I looked online and found a few ways to do it, they all say to insert some code here:
<?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', get_post_format() ); ?> <?php /* Insert here */ ?> <?php endwhile; ?>
For each of the sidebars it should be something like
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('Post widget 1') ) : ?> <?php endif;?>
…with the appropriate names filled in.
However, for some reason none of the things I found online actually specify (or specify correctly) which sidebar goes underneath which post. Whenever I got the sidebars to show up, they’d ALL show up underneath ALL posts. That’s not good, I just want the first sidebar underneath the first post, the second sidebar underneath the second post and so on.
I think what needs to happen is that I need to tell the while loop to only show Post widget 1 after post 1 etc. by having it do something different for each iteration, but I cannot figure out how (I’m not experienced with PHP, and everything I tried actually prevented the sidebars from showing up altogether, ha).
I don’t know if I’m thinking along the right lines there, but even if I am I can’t work out how to code it in PHP properly. Any help is much appreciated!
<?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', get_post_format() ); ?> <?php /* Insert here */ ?> <?php if( $wp_query->current_post <= 2 ) dynamic_sidebar('Post widget '. ($wp_query->current_post+1)); ?> <?php endwhile; ?>
- The topic ‘Insert sidebars between posts – how do I code this in my index.php?’ is closed to new replies.