WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] How can I exclude sticky post from custom loop? (4 posts)

  1. earthshaver
    Member
    Posted 1 year ago #

    I inserted a custom-loop in my template and the custom-loop would display 4 random entries. Everything went smoothly until used a sticky post. The custom-loop which should displayed only 4 entries now displayed 5 entries which messed up the design.

    Can anyone tell me how to exclude sticky post from custom loop?

    oh... and here's my custom-loop code:

    <div id="random-posts">
    <?php
    $my_query = new WP_Query('orderby=rand&showposts=4');
    while ($my_query->have_posts()) : $my_query->the_post();
    ?>
    
      [SOME STUFF]
    
    </div><!-- #random-posts -->
    
    <?php endwhile; ?>
    <?php wp_reset_postdata(); ?>
  2. esmi
    Forum Moderator
    Posted 1 year ago #

    Try:

    $my_query = new WP_Query('orderby=rand&posts_per_page=4&post__not_in=' . get_option( 'sticky_posts' ));

    Codex reference

  3. keesiemeijer
    moderator
    Posted 1 year ago #

    Try it with this [untested]:

    <div id="random-posts">
    <?php
    $args = array(
    'posts_per_page' => 4,
    'orderby' => 'rand',
    'post__not_in' => get_option( 'sticky_posts' )
    );
    $my_query = new WP_Query($args);
    while ($my_query->have_posts()) : $my_query->the_post();
    ?>
    
      [SOME STUFF]
    
    </div><!-- #random-posts -->
    
    <?php endwhile; ?>
    <?php wp_reset_postdata(); ?>

    http://codex.wordpress.org/Function_Reference/WP_Query#Sticky_Post_Parameters

  4. earthshaver
    Member
    Posted 1 year ago #

    Thanks for the quick reply, guys!

    Esmi's code doesn't work for me. But keesiemeijer's works like magic :)

Topic Closed

This topic has been closed to new replies.

About this Topic