Search code examples
phpwordpresscustom-post-typemeta

wordpress : how to add commas between meta terms on single custom post type


extendeing may last question about how to change the display of meta on single custom post type, with a great thanks to TimRDD for his helpful answer, now i have another question. the working generating code

<?php
//get all taxonomies and terms for this post (uses post's post_type)
foreach ( (array) get_object_taxonomies($post->post_type) as $taxonomy ) {
  $object_terms = wp_get_object_terms($post->ID, $taxonomy, array('fields' => 'all'));
  if ($object_terms) {
    echo '- '.$taxonomy;
foreach ($object_terms as $term) {
    echo '<a href="' . esc_attr(get_term_link($term, $taxonomy)) . '" title="' . sprintf( __( "View all posts in %s" ), $term->name ) . '" ' . '>' . $term->name.'</a> ';
}
    }
  }
}
?>

displays the terms in a single row but without commas between them such as : (- Proceeding2015 - keywordsbusinessconsumerresearch).

I need your help please to put (:) after every set of terms and commas between terms to display them such as : (- proceeding : 2015 - keywords : business, consumer, research).


Solution

  • You're code is ok, you just need to modify the output a bit. Try this code:

    //get all taxonomies and terms for this post (uses post's post_type)
    foreach ((array) get_object_taxonomies($post->post_type) as $taxonomy) {
        $object_terms = wp_get_object_terms($post->ID, $taxonomy, array('fields' => 'all'));
        if ($object_terms) {
            echo ': (- ' . $taxonomy . ': ';// I modify the output a bit.
            $res = '';
            foreach ($object_terms as $term) {
                $res .= '<a href="' . esc_attr(get_term_link($term, $taxonomy)) . '" title="' . sprintf(__("View all posts in %s"), $term->name) . '" ' . '>' . $term->name . '</a>, ';
            }
            echo rtrim($res,' ,').')';// I remove the last trailing comma and space and add a ')'
        }
    }
    

    Hope it works.