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?
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.