WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Displaying a div after a post while changing position based on number of posts (4 posts)

  1. YouKnowItMedia
    Member
    Posted 2 years ago #

    Hey everyone, I can't seem to find this answer clearly on the internet so I'm going to ask it myself, sorry if there is a thread for this or I am posting in the wrong place.

    what i'm trying to accomplish is to show a div after a certain amount of posts, which I have no problem doing, but I can't figure out how to do this: have where it displays (after post one or two or etc) change based on the total number of posts display at the time.

    What I want is my div, in this case "tagcloud_manual", to display after the forth post ONLY if the total number of posts is greater than 4, than to have it display after the 3rd post if the total number of posts is less than or equal to 3, than display after the second post if the total number of posts is 2 or less etc.

    right now the code will display my div after the 4th post no matter what, and if there are less than 4 posts it wont display :/

    my loop:

    <?php /* Start the Loop */ ?>
    <?php $count = 0; ?>
    <?php while ( have_posts() ) : the_post(); ?>
    <?php get_template_part( 'loop', get_post_format() ); ?>
    <?php if ($count == 3) : ?>
    <div class="tagcloud_manual">
    </div>
    <?php endif; ?>
    <?php $count++; ?>
    <?php endwhile; ?>

    [Moderator Note: Please post code or markup snippets between backticks or use the code button.]

  2. alchymyth
    Forum Moderator
    Posted 2 years ago #

    $wp_query->post_count gives you the actual number of posts in the loop;

    try:

    <?php /* Start the Loop */ ?>
    <?php $count = 0; $output = min(3, $wp_query->post_count-2); ?>
    <?php while ( have_posts() ) : the_post(); ?>
    <?php get_template_part( 'loop', get_post_format() ); ?>
    <?php if ($count == $output) : ?>
    <div class="tagcloud_manual">
    </div>
    <?php endif; ?>
    <?php $count++; ?>
    <?php endwhile; ?>
  3. david.bailey
    Member
    Posted 2 years ago #

    Use this code:

    <?php /* Start the Loop */ ?>
    <?php $count = 0; ?>
    <?php while ( have_posts() ) : the_post(); ?>
    <?php get_template_part( 'loop', get_post_format() ); ?>
    <?php global $wp_query;
    $num_posts = $wp_query->post_count;
    if ( ( ( $num_posts <= 3 ) && ( $count == $num_posts ) ) || ( $count == 4 ) ) echo '<div class="tagcloud_manual"></div>';
    $count++
    endwhile; ?>

    Tell me how it works out

    EDIT: Someone beat me to it - well now you have two code choices!

  4. YouKnowItMedia
    Member
    Posted 2 years ago #

    awesome guys both work perfect!

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.