Is it possible to edit the main query on a page using the pre_get_posts filter?
I tried but it doesn't seem to work.
function pre_wp_queries( $query ) {
// only trigger on main qyery
if ( !$query->is_main_query() )
return;
if (is_page_template('TEMPLATE_NAME.php')) {
$query->query_vars['pagename'] = null;
$query->query_vars['post_type'] = 'post';
$query->query_vars['posts_per_page'] = 3;
$query->query_vars['cat'] = 13;
}
}
add_action('pre_get_posts', 'pre_wp_queries', 9001);
On the header.php I use this line to check if it worked:
var_dump($GLOBALS['wp_query']->request);
It displays:
SELECT wp_posts.*
FROM wp_posts
WHERE 1=1
AND wp_posts.post_type = 'post'
ORDER BY wp_posts.post_date DESC
So it changed the posttype but not the rest. Also it goes to the 404 page. In fact dumping the $GLOBALS['wp_query']->queried_object gives back the original page. I tried this on 2 WP installs same behaviour on both.
Is this correct behaviour, or am I missing something?
function pre_wp_queries($q) { $q->set('posts_per_page', 3); }Just to see if it works? (tested in a sandbox myself and it works). You may also need to check that there aren't anyquery_postscalls in the template, they will overrule anything done in thepre_get_postshook, afaik. – totels Nov 12 '12 at 10:40query_posts. I know it's bad for performance. Consider closed. – janw Nov 12 '12 at 14:20