Using pre_get_posts to set posts per page, how do I?

I am trying to use pre_get_posts to set posts per page for a single term within a taxonomy. One thing that is throwing me off is setting the term to apply the pre_get_posts to.

Here’s my code:

function filter_press_tax( $query ){
if( $query->query_vars['tax_query']['taxonomy'] == 'press' && $query->query_vars['tax_query']['terms'][0] == 'press' ):
    $query->query_vars['posts_per_page'] = 5;
    return;
endif;
}//end filter_press_tax

I’m not quite understanding how to access the taxonomy and term in the $query. Yes the taxonomy and term have the same name. Is this a bad idea? I do not have a custom query set up on the taxonomy-press-press.php template for the ‘tax_query’ is this the problem?

Any help is appreciated! Thanks

Solutions Collecting From Web of "Using pre_get_posts to set posts per page, how do I?"

You’re almost there mate. Try this though.

<?php
    add_action('pre_get_posts', 'filter_press_tax');

    function filter_press_tax( $query ){
        if( $query->is_tax('press') && $query->has_term('press')):
            $query->set('posts_per_page', 5);
            return;
        endif;
    }
?>

You can use any conditional tag or any argument that can be passed to WP_Query to test your condition or set a new value via pre_get_posts. Also try $query->get('taxonomy') / $query->get('term').
And check this for $query‘s set and get methods.