4

I'm trying to replace the $wp_query object for a specific category, without having to deal with creating a new template and creating a new WP_Query object there.

My aim is to change the data available to The Loop from the default for that request to a custom query.

add_filter( 'pre_get_posts', 'custom_wpquery' );

function custom_wpquery( $query ){
global $wp_query;
   if (is_category(121)) {
             if ($wp_query === $query) {
                   $query = new WP_Query('page_id=146');
                   $query->set('page_id', 146);
             }
   }
  return $query;
};

That doesn't seem to affect The Loop at all, what am I doing wrong?

1 Answer 1

1

This seems to work, but I would be interested in hearing from others if it's the "correct" way to provide this sort of override. I'm assuming you're visiting a category archive page, like http://www.example.com/category/computers/.

// landing page = 188
// category = "computers" (#8)

function custom_wpquery( $query ){
    // the main query
    global $wp_the_query;

    if ( 'computers' === $query->get( 'category_name' ) ) {
        if ( $wp_the_query === $query) {
            // reset and override the active query
            $query->init();
            $query->query( 'page_id=188' );
        }
    }
};
add_filter( 'pre_get_posts', 'custom_wpquery' );

This should probably test $query->is_archive, as well.

3
  • A couple thoughts not specific to the question: you need to return $query because it's a filter, and in 3.3 you'll be able to use is_main_query() instead of global-ing and comparing to $wp_the_query. Also, you might as well combine the two if's :) Oct 16, 2011 at 15:20
  • pre_get_posts is an action (do_action_ref_array()), and $query is passed by reference, so $query doesn't need to be returned. Good point, regarding the combined if. Oct 16, 2011 at 16:02
  • 1
    Ah, you're right. I've only ever used it as a filter, and have been conditioned to go "OH NO" if I see a filter without a return :) Oct 19, 2011 at 14:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.