WordPress Alternating main loop (pre_get_posts filter) Even more specific loop targeting


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;
    if( !is_post_type_archive( 'book' ) ) return;

    // this code will run only if
    // - this query is main query
    // - and this is not admin screen
    // - and we are on 'book' post type archive page

You can also check for category, tag or custom taxonomy archive page using is_category(), is_tag() and is_tax().

You can use any conditional tag available in WordPress.