Answer the question
In order to leave comments, you need to log in
How to display category names (from custom taxonomy) separated by commas but without trailing commas?
1. On the WordPress site, on the post page (custom post type), the following code is used to display category names without a link (custom taxonomy category 'genres'):
<?php
$cur_terms = get_the_terms( $post->ID, 'genres');
foreach( $cur_terms as $cur_term ){
echo array_shift( $cur_terms )->name. ', ';
}
?>
<?php
$posts = get_field('relationship-field');
if( $posts ): ?>
<?php foreach( $posts as $post): // variable must be called $post (IMPORTANT) ?>
<?php setup_postdata($post); ?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php endforeach; ?>
<?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
<?php endif; ?>
Answer the question
In order to leave comments, you need to log in
for the first one like this:
<?php
$array = array();
$cur_terms = get_the_terms( $post->ID, 'genres');
foreach( $cur_terms as $cur_term ){
$array[] = $cur_term->name;
}
$comma_separated = implode(", ", $array);
echo $comma_separated; // term1, term2, term3
?>
<?php
$posts = get_field('relationship-field');
if( $posts ):
$new_posts = array(); ?>
<?php foreach( $posts as $post): // variable must be called $post (IMPORTANT) ?>
<?php setup_postdata($post);
$new_posts[] = '<a href="'.get_the_permalink().'">'.get_the_title().'</a>'; // сложили все в массив
?>
<?php endforeach;
$done_post = implode(",", $new_posts);
echo $done_post; ?>
<?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
<?php endif; ?>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question