WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question

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->query( 'page_id=188' );
add_filter( 'pre_get_posts', 'custom_wpquery' );

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

share|improve this answer
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 :) – helenhousandi Oct 16 '11 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. – Annika Backstrom Oct 16 '11 at 16:02
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 :) – helenhousandi Oct 19 '11 at 14:37

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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