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 want to filter my query results just before the_loop starts in word press. I only want the results having term_id or term_taxonomy_id equal to 1.

query_posts('post_type=my_post&term_id=1&posts_per_page=6');

This is returning all rows, I am new to word press so I am not sure that we can use term_id in query_posts. Is there any other way to do it?

share|improve this question
2  
Please simply don't use query_posts(). Read more about the why here wordpress.stackexchange.com/questions/1753/… –  kaiser May 19 '13 at 20:19

1 Answer 1

There is no term_id parameter. You need a tax_query.

$args = array(
    'post_type' => 'my_post',
    'posts_per_page' => 6,
    'tax_query' => array(
        array(
            'taxonomy' => 'yourtaxname',
            'field' => 'id',
            'terms' => 1
        )
    )
);
$query = new WP_Query( $args );

Notice that I've use new WP_Query and not query_posts. Don't use query_posts.

Doing the above will create a new query. That is, it will request information from the data in addition to any information that has already been requested. That is fine, if that is what is what you need but if possible, it is better to alter the main query before any posts are retrieved. This reduces the load on the server which should translate into a quicker load time for the site.

To interrupt the main query use pre_get_posts. This would be the equivalent code for doing that.

function restrict_tax_wpse_100006($qry) {
  if (is_page('somepage_id_title_or_slug')) {
    $qry->set('post_type','my_post');
    $qry->set('posts_per_page',6);
    $qry->set('tax_query', 
        array( 
             array(
                  'taxonomy' => 'yourtaxname',
                  'field' => 'id',
                  'terms' => 1 // or array(1)
             ) 
        )
    );
  }
}
share|improve this answer

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.