Wordpress - Getting posts in a custom taxonomy

2020-02-13 04:57发布

问题:

Ive been struggling with a wordpress issue for a few weeks now and i just cant figure it out.

I have created a custom post type called 'cpt_used', in that custom post type i have created a custom taxonomy called 'tax_used', which is a categories list

What i need to do is show all posts that belong to each custom taxonomy and i just cant figure it.

the code i have at the moment is as follows, there are multiple posts in each of the categories, but its just not displaying anything

$args = array(
    'orderby' => 'name',
    'hide_empty' => 0,
    'taxonomy' => 'tax_used'
);
$categories = get_categories($args);

foreach( $categories as $category ) {

    $newargs = array(
        'category_name' => $category->slug,
        'taxonomy' => 'tax_used',
        'term' => 'cpt_used'
    );

    query_posts( $newargs );
    if (have_posts()) :
        while (have_posts()) : the_post();
            the_title();
        endwhile;
    endif;

}

回答1:

$newargs are totally messed. try this:

$newargs = array(
 'post_type' => 'cpt_used',
 'tax_query' => array(
  array(
   'taxonomy' => 'tax_used',
   'field' => 'slug',
   'terms' => $category->slug
  )
 )
);

and remember print_r() sometimes returned values to check if it is exactly what you want before you start to iterate it ;)



标签: wordpress