Force index.php have_posts() loop to exit if no sticky posts found

I’m currently using the code below to list sticky posts on my index.php.

However, when no sticky posts are present, its loading the latest posts (up to the number specified in “settings > reading > blog posts show at most _ posts”.

Read More

How can I alter the script so that if there are no sticky posts, it exits out of the while?

query_posts(array('post__in'=>get_option('sticky_posts')));

if (have_posts()) :
while (have_posts()) : the_post();

Related posts

Leave a Reply

3 comments

  1. That is because get_option will return an empty array if there are no sticky posts and the query will default to everything.

    $sticky = get_option('sticky_posts');
    if (!empty($sticky)) {
      $args['post__in'] = $sticky;
      $qry = new WP_Query(array('post__in' => $sticky));
      if ($qry->have_posts()) :
        while ($qry->have_posts()) : $qry->the_post();
          echo $post->post_title;
        endwhile;
      endif;
    }
    

    And please don’t use query_posts.

  2. For starters, before we get to the essential issue, there is never hardly ever a reason to use query_posts. It should be treated as if deprecated – mostly anyway.

    It does not reset, but overwrite the main query after that has already been executed anyway.

    Much rather, use either the get_posts function or a new instance of the WP_Query class:

    $args = array(
        'post__in' => get_option( 'sticky_posts' ),
        'post_status' => 'publish'
    );
    
    $stickies = new WP_Query( $args );
    
    if ( $stickies->have_posts() ) {
        while ( $stickies->have_posts() ) {
            $stickies->the_post();
            // do something
        }
    }
    
    // reset the $post global to its previous state
    wp_reset_postdata();
    

    If, regardless of whether sticky posts were found, you’d like to alter the main query to return nothing (on the home page), make use of the pre_get_posts action:

    function wpse_96219_nothing_on_home( $query ) {
        if ( is_home() ) {
            $query->set( 'posts_per_page', 0 );
        }
    }
    add_action( 'pre_get_posts', 'wpse_96219_nothing_on_home' );