Last active
January 23, 2018 12:46
-
-
Save pixeline/9b466e0ff4656c1a0d3e to your computer and use it in GitHub Desktop.
Optimized Wordpress "pre_get_posts" boilerplate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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