speed up wp_query with pre_get_posts

// in functions.php
function my_post_queries( $query ) {
// do not alter the query on wp-admin pages and only alter it if it's the main query
if (!is_admin() && $query->is_main_query()){

// alter the query for the home and category pages
// well, it works for the pagination of the vertalers-category on the frontpage!
// see: http://codex.wordpress.org/Pagination#static_front_page
if(is_home()){
$query->set('posts_per_page', 6);
}

if(is_category('blog')){
$query->set('posts_per_page', 4);
}

//if ( $category_to_check = get_term_by( 'alle branches' ))
//post_is_in_descendant_category($category_to_check->term_id); {
//$query->set('posts_per_page', 100);
//}

}
}
add_action( 'pre_get_posts', 'my_post_queries' );

of deze:
// veranderd de volgorde van de agenda-actueel in admin, zodat deze overéénkomt met de 'voorpagina':
function set_post_order_in_admin( $wp_query ) {
if ( is_admin() && is_category( 'agenda-actueel' ) && !isset($_GET['orderby'])) {
$wp_query->set( 'orderby', 'date' );
$wp_query->set( 'order', 'ASC' );
}
}
add_filter('pre_get_posts', 'set_post_order_in_admin' );

Here is a small example using is_main_query and pre_get_posts:
// Load our function when hook is set
add_action( 'pre_get_posts', 'rc_modify_query_exclude_category' );
// Create a function to excplude some categories from the main query
function rc_modify_query_exclude_category( $query ) {
// Check if on frontend and main query is modified
if ( ! is_admin() && $query->is_main_query() && ! $query->get( 'cat' ) ) {
$query->set( 'cat', '-5' );
} // end if
}

In the code below, we are targeting only custom post type called “portfolio” where meta key “project_type” is set to “design”, that’s a typical query that can be used on a portfolio page:
// Load our function when hook is set
add_action( 'pre_get_posts', 'rc_modify_query_get_design_projects' );
function rc_modify_query_get_design_projects( $query ) {

// Check if on frontend and main query is modified
if( ! is_admin() && $query->is_main_query() && $query->query_vars['post_type'] != 'portfolio' ) {

$query->set('meta_key', 'project_type');
$query->set('meta_value', 'design');

}

}

Author: Jakob

Wordpress & bicycle enthusiast

Geef een reactie

Het e-mailadres wordt niet gepubliceerd. Vereiste velden zijn gemarkeerd met *