Tutorial by Examples

Let's say we want to change main loop, only for specific taxonomy, or post type. Targeting only main loop on book post type archive page. add_action( 'pre_get_posts', 'my_callback_function' ); function my_callback_function( $query ) { if( !$query->is_main_query() || is_admin() ) return;...
add_action( 'pre_get_posts', 'single_category' ); function single_category( $query ) { if( !$query->is_main_query() || is_admin() ) return; $query->set( 'cat', '1' ); return; }
Sometimes you would like to change main WordPress query. Filter pre_get_posts is the way to go. For example using pre_get_posts you can tell main loop to show only 5 posts. Or to show posts only from one category, or excluding any category etc. add_action( 'pre_get_posts', 'my_callback_function' ...
add_action( 'pre_get_posts', 'single_category_exclude' ); function single_category_exclude( $query ) { if( !$query->is_main_query() || is_admin() ) return; $query->set( 'cat', '-1' ); return; }
All we need to do is to use set() method of $query object. It takes two arguments, first what we want to set and second what value to set. add_action( 'pre_get_posts', 'change_posts_per_page' ); function change_posts_per_page( $query ) { if( !$query->is_main_query() || is_admin() ) retu...
WordPress is applying pre_get_posts filter to literally any loop it generates. It means that all changes we are making in our callback function are applied to all exiting loops. Obviously it is not what we want in most scenarios. In most cases we would like to target only main loop, and only for n...

Page 1 of 1