• Hi there,
    I’m working on my loop to show only the posts having some terms.
    The way I’m doing it now (inside the loop with has_term(array(), ‘category’)) fails because it is only returning 1 result, but this is not my biggest concern, the problem is that, if I place this conditional inside the loop I do not affect the pagination: for example, if I only have a post with the term “travel” the post will be displayed but the pagination will work like if all the post are listed.
    Do I have to put the loop inside the conditional (don’t know how to), so it only loops inside the posts matching the conditions given or should I do something to modify the pagination according to the matching results?

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    You should alter the query so that only posts with those terms are returned in the first place, this way the pagination will work properly without any extra effort. This is done with the ‘pre_get_posts’ action. Set one of the query vars listed here to limit posts containing certain category terms.

    The biggest challenge is determining which conditions to check before altering the query. ‘pre_get_posts’ fires for all queries, and you wish to restrict only a certain query. Besides there being a large selection if is-*() template tags (is_single(), is_archive() etc.), anything within the query itself could be used to distinguish your query from all others. Temporarily place the following code on your template where you were trying to alter the loop (but outside the loop) to see the entire query. Identify something unique you can use in a conditional, especially under [query_vars].

    <pre><?php
      global $wp_query;
      if($wp_query->is_main_query()) {
        print_r( $wp_query );
      }
    ?></pre>

Viewing 1 replies (of 1 total)
  • The topic ‘Conditioning the loop, not the results displayed’ is closed to new replies.