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 get a set of posts from a CPT based on a taxonomy term being present. I thought I'd use WP's get_posts() function:

$results = get_posts(array $options);

This function works fine when I specify the CPT i'm interested in:

$results = get_posts( array('post_type' => 'my_cpt_name') );

But then I tried this with my UOM custom post type and tried to filter on the metric system which is a taxonomy called "uom_system":

$results = get_posts( array('post_type' => 'uoms', 'uom_system' => 'metric-system' );

Sadly, the taxonomy section gets ignored and I get the full list of posts in the UOM posts table. What am I doing wrong?

share|improve this question
    
What are your register_taxonomy() arguments? –  TheDeadMedic Nov 8 '12 at 11:50
add comment

2 Answers 2

I solved my own problem by realising that the array I was passing into get_posts had some name-value pairs that were not intended for that function (aka, i was using it broadly to represent "options" to which only some of these options were for the get_posts call). It appears that rather than ignoring values it doesn't understand it stops processing further name-value pairs. Fair enough. I removed the junk name-value pairs and it works fine now.

I did like Simon's contribution around 'tax_query' ... I hadn't known of that option and I can see that this might be better syntax in certain circumstances.

share|improve this answer
add comment

I usually use the tax_query parameter:

$args = array(
    'post_type'      => 'my_cpt_name',
    'post_status'    => 'publish',
    'posts_per_page' => -1,
    'tax_query'      => array( array(
            'taxonomy' => 'uom_system',
            'field'    => 'slug',
            'terms'    => 'metric-system'
            ) )
    );

$results = get_posts( $args );

See http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters

share|improve this answer
add comment

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.