Setting posts_per_page for taxonomy term template

I have a custom taxonomy term page set up to display posts associated with that term (taxonomy-insight_type-academia.php). I figured I could use the following to limit the posts on that page based on code found here:

https://developer.wordpress.org/reference/functions/is_tax/

add_action( 'pre_get_posts', function( $query) {
    if ( $query->is_tax( 'academia', 'insight_type' ) ) {
        $query->set( 'posts_per_page', 1 );
    }
} );

I have added the term to the taxonomy but it doesn’t seem to work. I can get it to work for the taxonomy, but not the term.

Is there a way to do this?

Thanks

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The taxonomy template you have (taxonomy-insight_type-academia.php) is in the form of (taxonomy-{taxonomy}-{term}.php), and the format for is_tax() is is_tax( '<taxonomy>', '<term>' ), so in your pre_get_posts callback, you should:

// Use this.
if ( $query->is_tax( 'insight_type', 'academia' ) )

// Not this.
if ( $query->is_tax( 'academia', 'insight_type' ) )

Additionally — to avoid conflict with other queries, you should also check if the current query is the main one or not, and also check if it’s an admin-side request.

if ( ! is_admin() && $query->is_main_query()
    && $query->is_tax( 'insight_type', 'academia' )
)

You may already know that, but I thought it’d be a good reminder. 🙂


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x