How do I display the taxonomy for a custom post type in an array

Neelam Khan asked
custom-post-types custom-taxonomy taxonomy get-terms

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) {
   $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?


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.
Share This
Posted in: