How to filter WordPress Query?

WordPress provides pre_get_posts to change main query.This action hook gives developers access to the $query object by reference and we can modify the $query object to filter the results.We can use it for search page,archive page,category page etc.

You can define this hook in functions.php or plugin files.

 
Signature of the hook is as below.

add_action('pre_get_posts','your_function_name');

<?php

//To exclude a category from main query.

function exclude_category( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'cat', '10' );
}
}
add_action( 'pre_get_posts', 'exclude_category' );

//To display 50 posts per page for custom post named product

function set_pagesize( $query ) {

if ( $query->is_home() && $query->is_main_query() ) {

if ( is_post_type_archive( 'product' ) ) {
// Display 50 posts for a custom post type called 'product'
$query->set( 'posts_per_page', 50 );
return;
}

}

}

add_action( 'pre_get_posts', 'set_pagesize' );

?>

Leave a Reply