0

I'm using twenty twelve and I need to insert a div between the posts. I'm not sure how to stop the loop, insert the div, and then restart the loop.

Can anyone shed some light on this? Thanks.

  • what you mean stop the loop, insert the div, and then restart the loop? – Anjum Sep 13 '13 at 18:32
  • I was thinking a PHP script was used to loop through all the posts and echo them all out. – Stephen Sep 13 '13 at 18:56
1

You can check your position within the loop using the current_post var of the $wp_query object, and insert markup at a specific spot or at some interval. A simple example:

while( have_posts() ):
    the_post();

    the_title();
    the_excerpt();

    // if current_post is 1, insert the div
    // note that current_post starts at 0,
    // so this will be after the second post's content

    if( 1 == $wp_query->current_post ):
        echo '<div>My div!</div>';
    endif;

endwhile;
  • Perfect - that's exactly what I was looking for. Does this solution have anything to do with why my posts are cut off with [...] instead of showing full text? I was thinking that they showed full text before. – Stephen Sep 13 '13 at 19:24
  • change the_excerpt() to the_content() to show full post content. – Milo Sep 13 '13 at 19:33
  • Got it. Can you tell me which file that WP defines these objects/methods so I can research this on my own? I've been combining through these files for a few hours now and cannot find the methods anywhere. – Stephen Sep 13 '13 at 19:39
  • You can see the internals of the query engine WP_Query in wp-includes/query.php – Milo Sep 13 '13 at 21:46
  • @Milo I have a wordpress site that uses the infinite scroll for the post lists on the homepage. I want to display a div between posts too but the loop works only for the first page (8posts per page). Can you please help me out – AndrewL64 Jul 12 '15 at 19:05
-1

You can add the <div> right after the post is output by modifying index.php of the theme. Take a look at lines 22-25 (http://themes.trac.wordpress.org/browser/twenty-twelve/0.9/index.php), you'd place it right after line 24, which is responsible for pulling the right content type template in and displaying it.

<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
    <?php get_template_part( 'content', get_post_format() ); ?>
    <!-- You could insert your div here -->
<?php endwhile; ?>

If you wanted to get picky about which types of posts (regular posts, image posts, etc.) it comes after, then you could edit the content-*.php files themselves, and place it at the end of those templates.

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.