How do I add custom variables to the wordpress query without having to hit the database twice. In the example below I want to add some meta filters. All this code works fine but I have been running query_posts() to execute it. I want to be able to add to the query before it is run by default so I don’t have to query the db twice.
In this I was hoping if I modify $wp_query->query before it is executed my changes would be added to the query. The query is being changed fine, just not the output. Any ideas? Thanks.
add_action('pre_get_posts', 'my_custom_query');
function my_custom_query(){
if(isset($_SESSION['size']) && $_SESSION['size'] != 'all'){
$cfilter[] = array( 'key' => 'cc_size', 'value' => $_SESSION['size'] );
}
if(isset($_SESSION['gender']) && $_SESSION['gender'] != 'all'){
$cfilter[] = array( 'key' => 'cc_gender', 'value' => $_SESSION['gender'] );
}
$extraArgs = array(
'orderby' => 'post-title',
'paged' => get_query_var('paged')
);
if(!empty($cfilter)){ $extraArgs['meta_query'] = $cfilter; }
global $wp_query;
$wp_query->query = array_merge( $wp_query->query, $extraArgs );
}
As toscho said, you can modify the query in the
pre_get_posts
hook. That hook gets the query object passed as an argument, so you don’t have to read a global variable.I see that your query depends on session variables. This can make it harder to forward a link to a page to someone else. Have you considered putting this in the URL and reading it from there? You can do that by creating extra rewrite rules.
Hook into the action
'pre_get_posts'
.Example: