There are a number of 3rd party wp.org repository plugins that 1) add categories and tags to pages, and 2) enable pages to be displayed along with posts in the archive pages.

The code they use for part 2 always uses:

$wp_query->set

eg:

   if ( ! is_admin() ) {
      add_action( 'pre_get_posts', 'category_and_tag_archives' );
   }

// Add Page as a post_type in the archive.php and tag.php 

function category_and_tag_archives( $wp_query ) {

    $my_post_array = array('post','page');

    if ( $wp_query->get( 'category_name' ) || $wp_query->get( 'cat' ) )
      $wp_query->set( 'post_type', $my_post_array );

    if ( $wp_query->get( 'tag' ) )
      $wp_query->set( 'post_type', $my_post_array );

  }

So the plugins are all modifying wp_query settings and then leaving these settings — ie they are not unsetting the changes or resetting them.

I guess they cannot reset wp_query because wp_query is not executed immediately after they modify it – wp_query will be executed at a later time when the archive page is called. Since they are not executing wp_query in their code they cannot reset it right after.

Then when I use this code in another plugin, eg:

$the_query = new WP_Query( array( 'cat' => $categoryid, 'post_type' => 'page' ) );

It returns both posts and pages, when it should only return pages.

This is because the wp_query has been modified and not reset.

I do not what to do in this case to get wp_query working for the second chunk of code.

The obvious would be to reset wp_query before my line of code but I am not sure it that will negatively affect other code in other plugins or the core.

Any help is greatly appreciated.

2 s
2

If the code shown above is the one the plugin is using, it will affect every query, since it’s not checking for is_main_query() (https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts)

What you could do, is remove the action, do your query, and then add the action again (if needed)

remove_action( 'pre_get_posts', 'category_and_tag_archives' );
$myQuery = new WP_Query($queryArgs);
add_action( 'pre_get_posts', 'category_and_tag_archives' );

If in the plugin it has a different priority (default is 10) make sure to specify it.

Heres the remove action reference https://codex.wordpress.org/Function_Reference/remove_action

Hope this helps,

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *