Chris
Chris

Reputation: 398

Wordpress, WP_Query with custom taxonomy and custom post type

This code gets 10 posts of all types that are linked to the term_name;

global $wp_query;
query_posts( array(  
    "taxonomy_name" => "term_name", 
    'showposts' => 10 ) 
);

This code gets 10 posts of custom post type "message";

global $wp_query;
query_posts( array(  
    'post_type' => 'message' 
    'showposts' => 10 ) 
);

This code however always ignores the post_type requirement but still selects all post types linked to the term_name;

global $wp_query;
query_posts( array(  
    'post_type' => 'message' ,
    "taxonomy_name" => "term_name",
    'showposts' => 10 ) 
);

I can't see how both can work individually but together they don't unless it might be a bug - any thoughts?

Upvotes: 4

Views: 16887

Answers (3)

Gus Liedke
Gus Liedke

Reputation: 1

Use 'category_name' instead 'taxonomy_name'. Works on WP 3.5.2

query_posts( array(  
    'post_type' => 'message',
    'category_name' => 'term_name',
    'showposts' => '10' ) 
);

Upvotes: 0

Chris
Chris

Reputation: 398

Been submitted - core.trac.wordpress.org/ticket/13020. Fix is just changing one line of the query.php file to and if statement to check whether post_type is empty.

Upvotes: 1

Rupert Madden-Abbott
Rupert Madden-Abbott

Reputation: 13278

Looks like a bug. Have you tried a custom select query? This should do it:

$querystr = "
    SELECT * 
    FROM $wpdb->posts
    LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)
    LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
    LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id)
    WHERE $wpdb->posts.post_type = 'message' 
    AND $wpdb->posts.post_status = 'publish'
    AND $wpdb->term_taxonomy.taxonomy = 'taxonomy_name'
    AND $wpdb->terms.slug = 'term_name'
    ORDER BY $wpdb->posts.post_date DESC
    LIMIT 10
    ";

$pageposts = $wpdb->get_results($querystr, OBJECT);

I used this answer in constructing the query.

Upvotes: 5

Related Questions