Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Optimized Wordpress "pre_get_posts" boilerplate
<?php
// In your theme's functions.php file.
add_action( 'pre_get_posts', 'alter_the_main_query' );
function alter_the_main_query( $wp_query ){
if(is_admin() || !$wp_query->is_main_query()){
// pre_get_posts is launched on ALL requests. So we get out early if this is a wp-admin url request or if this is not the main query.
return;
}
// FOO's category archive
if ($wp_query->is_category('foo-category-slug')){
// change number of posts to display
$wp_query->set( 'posts_per_page', '10' );
$wp_query->set( 'orderby', 'date' );
$wp_query->set( 'order', 'DESC' );
}
// Front page, used in a front-page.php template
if($wp_query->is_home()){
$wp_query->set( 'posts_per_page', '3' );
$wp_query->set( 'orderby', 'date' );
$wp_query->set( 'order', 'DESC' );
// exclude category 3
$wp_query->set( 'cat', '-3');
// Exclude sticky posts from main query
$wp_query->set('post__not_in', get_option('sticky_posts'));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.