Skip to content

Instantly share code, notes, and snippets.

@pixeline
Last active January 23, 2018 12:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pixeline/9b466e0ff4656c1a0d3e to your computer and use it in GitHub Desktop.
Save pixeline/9b466e0ff4656c1a0d3e to your computer and use it in GitHub Desktop.
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