0
votes

In WordPress, I am trying to get posts from a custom post type 'color', custom taxonomy 'color-name', using the following:

Notes: I have a custom post type, Color, with custom posts that are titled things like, 'Coral', 'Peony'. I also have a custom taxonomy, color-name. Through a hook on saving a color post, categories in that custom taxonomy get created. Then, the custom post type Color, can be tagged with other related colors.

$slug = str_replace(" ", "_", $page_title);
$slug = strtolower($slug);

//Slug is - 'coral', 'peony', etc.

$args = array( 'post_type' => 'color',
               'posts_per_page' => -1,
               'tax_query' => array( array (
                       'taxonomy' => 'color-name',
                       'field' => 'slug',
                       'terms' => $slug
                                   ) )
);
$myposts = query_posts( $args );

I've tried many variations of this after Googling, and nothing is working - I either get all posts, or no posts. Here's another version of args I've tried: (results in no posts):

  $args = array('color-name' => $page_title,
                'post_type' => 'color',
                'post_status' => 'publish',
                'posts_per_page' => -1,
                'caller_get_posts'=> 1
               );

I've wrestled with this before and gave up and just made a custom sql call. Does anyone know definitively how to get this working through WordPress functions?

1
How are you getting your terms. It seems that is your problem. Also, NEVER use query_posts, it breaks the main query and in most cases outright fails in pagination. Also, caller_get_posts is longtime depreciated, was replaced with ignore_sticky_posts - Pieter Goosen
You mean this piece? 'terms' => $slug? $slug is a string, like "peony". - heykatieben
Yes, I meant that. I believe $slug is your problem. Are you sure the result from $slug is a string and not an array. Please edit your question and add your code for $slug. I want to have a look at that - Pieter Goosen
Here's what I'm trying to do, in words: List all posts tagged 'blue' under a custom taxonomy called color-name, that are also in a custom post type 'color' - heykatieben
OK, that make a bit of sense. The part that doesn't, blue, is that a post tag or a term inside color-name - Pieter Goosen

1 Answers

1
votes

I would use WP_Query instead of query_posts(). For example:

$args = array(
    'post_type' => 'color',
    'tax_query' => array(
        array(
            'taxonomy' => 'color-name',
            'field' => 'slug',
            'terms' => $slug
        )
    )
);
$query = new WP_Query( $args );

if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        // Do something.
    }
} else {
    // No posts found.
}
wp_reset_postdata();

Ref: http://codex.wordpress.org/Class_Reference/WP_Query