最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

custom taxonomy - How to use get_the_terms() to display multiple terms?

programmeradmin2浏览0评论

I'm using the following code to display a custom taxonomy in the metadata for a single post, but now I need to display multiple terms separated by commas instead of just a single term. Just not sure how to do that. Is there a way to use something like wp_sprintf_l in combination with get_the_terms() to accomplish this? Or any other way?

Here's my current function:

$sources = get_the_terms( $post->ID, 'source' );
if ( ! empty( $sources ) && ! is_wp_error( $sources ) ){
foreach ( $sources as $source ) {
    $sourcename = $source->name;    
    }
$sourcelink = get_term_link( $source );
$sep2 = __( ',' );
}

Then I display it with this:

echo "<span class='source-meta'><a href='$sourcelink'>$sourcename</a>$sep2</span>;

I'm using the following code to display a custom taxonomy in the metadata for a single post, but now I need to display multiple terms separated by commas instead of just a single term. Just not sure how to do that. Is there a way to use something like wp_sprintf_l in combination with get_the_terms() to accomplish this? Or any other way?

Here's my current function:

$sources = get_the_terms( $post->ID, 'source' );
if ( ! empty( $sources ) && ! is_wp_error( $sources ) ){
foreach ( $sources as $source ) {
    $sourcename = $source->name;    
    }
$sourcelink = get_term_link( $source );
$sep2 = __( ',' );
}

Then I display it with this:

echo "<span class='source-meta'><a href='$sourcelink'>$sourcename</a>$sep2</span>;
Share Improve this question asked Apr 15, 2020 at 19:29 Jon FergusJon Fergus 791 silver badge10 bronze badges 1
  • 1 you are looping all the terms in the foreach loop, but you are not using any apart from the last one. just build the echo into the foreach loop... – Michael Commented Apr 16, 2020 at 1:49
Add a comment  | 

1 Answer 1

Reset to default 1

I'm going to go and test this somewhere so I may need to make edits, but I think this should do it for you... as Michael mentioned in the comments, you have to wrap the output in the foreach. The method below will place a comma after each one, so I wrap the separator commas in their own span and then use CSS to hide the last one.

$sources = get_the_terms( $post->ID, 'source' );
if( !empty( $sources ) && !is_wp_error( $sources ) ) {
    echo '<span class="source-meta">';
    foreach( $sources as $source ) {
        $source_link = sprintf(
            '<a href="%1$s">%2$s</a>%3$s',
            esc_url( get_term_link( $source ) ),
            esc_html( $source->name ),
            '<span class="sep">, </span>'
        ); 
        echo sprintf( esc_html__( '%s', 'textdomain' ), $source_link );   
    }
    echo '</span>';
}

In your stylesheet (style.css) you then want the following:

.source-meta .sep:last-of-type{
     display:none;
}
发布评论

评论列表(0)

  1. 暂无评论