wordpress - WP_Query sometimes returns zero results when there are matching posts - why? -
this 1 has got me stumped.
i have category.php file contains loop:
<?php if ( have_posts() ) : ?> <?php while ( have_posts() ) : the_post(); ?> <div class="entry-content description clearfix"> <h2 class="category-subtitle"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <?php echo the_content(); ?> <?php global $withcomments; $withcomments = 1; ?> </div><!-- .entry-content --> <?php endwhile; else : get_template_part( 'content', 'none' ); endif; ?>
this block of code works fine , returns results 1 expect.
in addition, outside loop (after it, in case matters), i've got column 1 side loop - i'm going refer newsfeed loop sake of clarity:
<h3 class="newsfeed-heading"><a href="/category/news/">latest news</a></h3> <?php // wp_reset_query(); * same results or without wp_reset_query $args = array( 'cat' => 89, 'order' => 'asc' ); $custom_query = new wp_query($args); //echo "<h2>found: $custom_query->found_posts</h2>"; while($custom_query->have_posts()) : $custom_query->the_post(); ?> <div <?php post_class(); ?> id="post-<?php the_id(); ?>"> <h4 class="highlight1"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4> <p><?php $content = get_the_content(); echo mb_strimwidth($content, 0, 160, '...');?></p><div class="morelink"><a title="<?php the_title(); ?>" href="<?php the_permalink(); ?>">read more</a></div> </div> <?php endwhile; // wp_reset_postdata(); * same results or without wp_reset_postdata ?>
now, in majority of cases, these 2 loops play nicely , both loops return set of results i'd expect. not always.
as far can tell, think if main category loop contains 1 result, newsfeed loop correct. if main category loop has multiple posts in results set, newsfeed loop works fine. have not been able spot pattern.
i have tried putting wp_reset_query();
in different places, clutching @ straws, doesn't make difference.
incidentally, when newsfeed loop works, returns correct results set. when doesn't, returns nothing , $custom_query->found_posts
returns zero.
i appreciate advice on possible solution.
you missing wp_reset_postdata();
after custom query. call the_post()
, setting $post
global value of current post. true main query , custom instance of wp_query
. in get_posts
, happens when call setup_postdata()
.
as pointed out, wp_reset_query()
used query_posts
should never use breaks main query object , relies on main query object related posts, pagination , page functionality.
if above not work, posts_**
filters or instance of pre_get_posts
poorly written in theme or plugin. apart these suggestions, code should work.
Comments
Post a Comment