Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

share|improve this question

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer
    
Thanks for this! The is_tax works great but still cannot set the term. has_term throws an error and using get('term') doesn't apply the posts per page. Tried using get('term') == slug, id and name values but with no luck. Then tried $query->query_vars['term'] also with no luck. I must still be missing something. Looked into the $query stdClass Obj here: codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts and don't see a 'term' or has_term value in the list. It works as long as I don't try and set the term. Strange. –  dkmojo Apr 2 '12 at 22:15
    
You're welcome! You want to set the term? Lemme take a look at it and see how it can be done. –  Rutwick Gangurde Apr 3 '12 at 3:53
    
Thanks! it works fine for the moment and my other term in the press taxonomy, called online reviews, isn't affected too terribly much. I look forward to anything you might find that could be helpful. :) –  dkmojo Apr 3 '12 at 15:21
    
Welcome again! Actually I don't have a cpt/taxonomy setup at hand right now, hence couldn't test it. But sure will test as soon as I set the things and update here. :D –  Rutwick Gangurde Apr 3 '12 at 16:32

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.