Overriding The Loop with filter or hook

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.

Leave a Comment