I am trying to show all records for a particular custom post type and I want a list of all taxonomies in a dropdown.

Here is the query for the CPT:

        $articles = new WP_Query(array(
        'posts_per_page' => -1,
        'post_type' => 'stories',

And getting the terms

$terms = get_terms( array(
    'taxonomy' => 'topic',
    'hide_empty' => false,
) );

Then the loop

<?php if ($articles->have_posts() ):
while ($articles->have_posts() ): $articles->the_post();
// this is where I want to echo all taxonomy names
 <div class="masonry__item col-lg-3 col-md-6" data-masonry-filter="<?php //echo tax names here ?>">

<?php endwhile; ?>
 <?php wp_reset_postdata(); ?>
<?php endif; ?>
  • You mean only those terms assigned to the current post? And you want it like so: Category 1, Category 2 (separated by comma) or is it by slug like so: category-1 category-2 (separated by space) – Sally CJ Nov 21 '19 at 11:20
  • No, I want to list all records for the custom post type and I also want to list all taxonomies associated with the custom post type. I am using isotope filter. So, the custom post type records show in columns and above is a filter dropdown with the taxonomy names. So, If I click on one of those then it will only show posts for that taxonomy name – user10980228 Nov 21 '19 at 11:29
  • I don't want it to be outputted with commas etc. I want to put the names in any container I want whether it be in a <li> or <option>. I just want the names. – user10980228 Nov 21 '19 at 11:30
  • There are differences between 'taxonomy' and 'term' - e.g. in your case, the taxonomy is 'topic' and a term inside that could be 'Topic 1', 'Topic 2', etc. So are you sure you want to list the taxonomy names and not term names? And do you want the names or the slugs (e.g. for a term, name: 'Topic 1', slug: 'topic-1')? – Sally CJ Nov 21 '19 at 11:39
  • Ah, right. Yes, I am looking for the term names. – user10980228 Nov 21 '19 at 13:23

I'm answering the <?php //echo tax names here ?>:

  1. In the loop, you can get the post terms using wp_get_post_terms():

    while ($articles->have_posts() ): $articles->the_post();
      $terms = wp_get_post_terms( get_the_ID(), 'topic', [ 'fields' => 'names' ] );
  2. Then you can do something like echo implode( ' ', $terms ); inside the <div> tag:

    <div class="masonry__item col-lg-3 col-md-6"
      data-masonry-filter="<?php echo implode( ' ', $terms ); ?>">

But are you very sure you want to use the term name and not slug?

If you want the term slug, then you'd use 'fields' => 'id=>slug' and not 'fields' => 'names'.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.