Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query posts by custom taxonomy ID

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!

like image 684
mattberridge Avatar asked Oct 07 '11 14:10

mattberridge


People also ask

How do I find the taxonomy of a WordPress post?

In WordPress, you can create (or “register”) a new taxonomy by using the register_taxonomy() function. Each taxonomy option is documented in detail in the WordPress Codex. After adding this to your theme's functions. php file, you should see a new taxonomy under the “Posts” menu in the admin sidebar.

What is taxonomy in custom post type?

Custom Taxonomy for Custom Post Types. Taxonomies are a great way to group things together and help us to search posts belonging to a specific group. In WordPress we generally use Categories and Tags as taxonomies. The steps given below explain how to create custom taxonomies for your CPT.


1 Answers

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

like image 152
mattberridge Avatar answered Oct 29 '22 16:10

mattberridge