Query posts by custom taxonomy ID
Asked Answered
F

2

7

I have a custom post type called portfolio and a custom taxonomy called build-type (acting as categories)

I am trying to query portfolio posts by build-type ID e.g. all Portfolio posts in "Hotels" (id=4 for that taxonomy)

// gets the ID from a custom field to show posts on a specific page   
$buildType = get_post_meta($post->ID, 'build_type_id', true);
// run query
query_posts(array( 
    'post_type' => 'portfolio',
    'showposts' => -1,
    'tax_query' => array(
        'taxonomy' => 'build-type',
        'terms' => $buildType,
        'field' => 'term_id'
    ),
    'orderby' => 'title',
    'order' => 'ASC'
));

Currently it's calling all portfolio posts and not just those with the build-type ID

For 'field' => 'term_id' should I be using term_id, tag_ID, id or something else?

Anyone know how to get this working?

Thanks in advance!

Flux answered 7/10, 2011 at 14:21 Comment(0)
F
19

I solved it with help from: https://wordpress.stackexchange.com/questions/30476/query-posts-by-custom-taxonomy-id

tax-query needs to be an array of arrays

The final solution is:

// gets the ID from a custom field to show posts on a specific page
$buildType = get_post_meta($post->ID, 'build_type_id', true);
// run query
query_posts(array( 
    'post_type' => 'portfolio',
    'showposts' => -1,
    'tax_query' => array(
        array(
            'taxonomy' => 'build-type',
            'terms' => $buildType,
            'field' => 'term_id',
        )
    ),
    'orderby' => 'title',
    'order' => 'ASC' )
);

On github here:

https://gist.github.com/1275191

Flux answered 19/10, 2011 at 8:25 Comment(0)
M
0

I'm not a WP-gury and I have invested hours and hours trying to solve the same problem. Eventually I found this blog post: http://richardsweeney.com/blog/wordpress-3-0-custom-queries-post-types-and-taxonomies/

The answer is somewhat semi-bad: apparently you can't filter like this for custom post types (it is only possible for posts), which is a shame!

What I did work was this:

$args['custom_tax'] = 'custom_tax_slug'; query_posts($args);

Hope it helps!

//Mike

Messner answered 18/10, 2011 at 1:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.