Support » Fixing WordPress » Sticky post issue: Why is a custom query returning posts when none should exist?

  • My home page has two loops with the following conditions:

    Home Loop 1: News Announcements (when category = 2 && sticky = true)
    Home Loop 2: Featured Post (when category != 2 && sticky = true)

    My blog page has two loops:

    Blog Loop 1: Featured Post (when category != 2 && sticky = true)
    Blog Loop 2: Recent Posts (all categories, where sticky = false)

    The issue I’m having:
    When I have no posts with a sticky status, Blog Loop 1 is still returning posts even though I believe it shouldn’t b/c my custom query should be scoped to sticky posts only. Interestingly, as soon as I make a New Announcement sticky, the Featured query returns empty.

    <?php
    	// display the most-recent sticky featured post
    	// exclude News Accouncements (category 2)
    	$args_featured_posts = array(
    		'category__not_in' => array( -2 ),
    		'post__in'  => $sticky,
    		'ignore_sticky_posts' => 1
    	);
    	$query_featured_posts = new WP_Query( $args_featured_posts );
    
    	print_r($query_featured_posts); // ISSUE: Why is this returning posts?
    ?>
    
    <?php if ( $query_featured_posts->have_posts() ) : ?>
    	<h1>Featured Post</h1>
    	<?php while ( $query_featured_posts->have_posts() ) : $query_featured_posts->the_post(); ?>
    		<?php get_template_part( 'content', 'single' ); ?>
    	<?php endwhile; ?>
    <?php	endif; ?>
    <?php wp_reset_postdata(); ?>
    
    <?php
    	$args_recent_posts = array(
    		'post__not_in' => $sticky
    	);
    	$query_recent_posts = new WP_Query( $args_recent_posts );
    ?>
    
    <?php if ( $query_recent_posts->have_posts() ) : ?>
    	<h1>Recent Posts</h1>
    	<?php while ( $query_recent_posts->have_posts() ) : $query_recent_posts->the_post(); ?>
    		<?php get_template_part( 'content', 'single' ); ?>
    	<?php endwhile; ?>
    <?php endif; ?>
    <?php wp_reset_postdata(); ?>
  • The topic ‘Sticky post issue: Why is a custom query returning posts when none should exist?’ is closed to new replies.