0
votes

i'm seeing some strange behaviour I cannot explain inside a category-based template loop.

i have a custom query filter for the category template, preselecting a couple of custom post types to query for:

add_filter( 'pre_get_posts', 'cust_posts_collection' );
function cust_posts_collection( $query ) {
  if ( (is_category() && $query->is_main_query()) )
    $query->set( 'post_type', array( 'cust_post_type_1', 'cust_post_type1' ) );
  return $query;
}

this results in a proper $wp_query object, containing among others an array of posts. let's say for a given category x there are 4 posts. when i var_dump $wp_query i can verify

["posts"]=>&array(4)

and i can see all the posts and their data in the dump.

however, when i loop then over that object:

<?php  if ( $wp_query->have_posts() ) while ( $wp_query->have_posts() ) : $wp_query->the_post();
  var_dump($post);
endwhile; ?>

all i see is two posts.

how is this possible?

are there any configuration defaults on the loop functions that i am missing?

1
Can you post the whole file with context? What are you assigning the query to? wp_query? - Wold

1 Answers

0
votes

I was able to solve the bug:

it turns out that there was another loop in the header partial, prior to the loop exposing the bug.

the first loop had a break statement right after an if conditional - the idea: find the first occurrence of a certain custom post type and then break out of the loop.

the problem: this break did not properly reset a global post index variable or something along those lines. the next loop then got a wrong state of the index, causing it to jump as many initial posts as had been looped over in the previous loop.

adding rewind_posts() just before the break fixed this for me.