You can just run through the loop and set a flag:
if ( $query->have_posts() ) :
$any_in_cat = false;
while ( $query->have_posts() ) : $query->the_post();
if ( in_category( 'first-major' ) ) :
$any_in_cat = true;
endif;
endwhile;
$query->rewind_posts();
/* if $any_in_cat == true at this point then at least one
of the posts has the category 'first-major'
*/
if( true == $any_in_cat ) {
echo 'true';
} else {
echo 'false';
}
I’ve added your conditional check. Note that it is all PHP, so you don’t want the opening and closing tags where you have them in your comment. I prefer the brace notation myself as it suits every case of nested conditionals and is really clear to read. Lastly you need the double-equals sign to test equality. =
is the assignment operator, so when you say if ( $any_in_cat = true )
then you are setting $any_in_cat
to true
and also the condition will always be true
. Even if ( $any_in_cat = false )
is true
because you are testing the success of the assignment. It’s a slip we all make and is easier to debug if you get in the habit of writing the condition as if( true == $any_in_cat )
Then if you slip and use a single =
you’ll get an error message as you can’t make an assignment to true
.
You’re re-running your loop several times, so it might be possible to simplify your code somewhat too, but that’s another question and not directly WP related.