1

I am trying to display the terms from a taxonomy on my archive page but I am struggling to display the terms name, here is what I have so far:

if ($post->post_type == 'cpt_saving') {
   $categories = get_the_terms($post->ID, 'cpt_saving-type');
   if ($categories) {
       $categories['name'];
   }
   $stack = [
        'title' => get_field('savings_headline', $post_id),
        'image' => get_field('savings_supplier_logo', $post_id),
        'reference' => get_field('savings_reference', $post_id),
        'date' => get_the_date('l j F Y'),
        'link' => get_the_permalink(),
        'term' => $categories->name,
    ];
    get_template_partial('partials/savings/savings-item', $stack);
}

As I have $stack as my array how would I call the taxonomy terms name to display it on the front end?

  • Have you tried print_r($stack['term']) (or with var_dump() to see if it outputs something? – Marcelo Henriques Cortez Nov 6 '17 at 11:30
  • get_the_terms returns an array (not single) of WP_Term objects. You'd want to loop through them and get the $name from each. If you want just the first then something around $categories[0]->name should work – LumberHack Nov 6 '17 at 11:51
0

As has already been noted, you can do this by iterating over each of the terms, which are WP_Term objects. Each of those WP_Term objects has a name property. So you'd do it like this:

$terms = get_the_terms( $post->ID, 'cpt_saving-type' );
$terms = is_array( $terms ) ? $terms : array();

foreach ( $terms as $term ) {
    echo $term->name.'<br />'; // Outputs each name.
}
  • I had already tried this prior to posting my question, unfortunately it doesn't work as it displays the same taxonomy term for all posts (even those without a term assigned to them). I have posted my solution below... – Neelam Khan Nov 7 '17 at 15:39
0

I was able to display the taxonomy term for each post using the following:

$savings_terms = get_the_term_list($post->ID, 'cpt_saving-type');

$stack = [
  'term' => strip_tags($savings_terms),
];

This output the current term for each post and doesn't throw an error when a post doesn't have a term assigned to it, it worked best for my situation.

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.