Using pre_get_posts to set the type of posts appearing on a Tag archive in WordPress

Posted on
5/5 - (456 votes)

Want to show 2 entries of a journal CPT on economics tag archive page?

Add the following in child theme’s functions.php:

add_action( 'pre_get_posts', 'sk_change_tag_term_archive_query' );
/**
 * Set only Journal CPT entries (two of them) to appear on Economics Tag Archive
 *
 * @param object $query data.
 */
function sk_change_tag_term_archive_query( $query ) {

    if ( $query->is_main_query() && ! is_admin() && is_tag( 'economics' ) ) {
        $query->set( 'post_type', array( 'journal' ) );
        $query->set( 'posts_per_page', '2' );
    }

}

Instead of a standard tag taxonomy, if you have a custom taxonomy called say, journal_tag, you’d replace

is_tag( 'economics' )

with

is_tax( 'journal_tag', 'economics' ).