25% off ProSNIPC25OFF

Display Current Post's Taxonomy Terms via Shortcode

Shortcode [post_terms taxonomy="category"] lists the terms of any taxonomy assigned to the current post.

PHPby SnipCraft
php
<?php
/**
 * Usage: [post_terms]
 *        [post_terms taxonomy="post_tag" sep=" | " links="false"]
 * Attributes:
 *   taxonomy — taxonomy slug (default: "category")
 *   sep      — separator string (default: ", ")
 *   links    — "true" (default) wraps each term in its archive link; "false" outputs plain text
 */
add_shortcode( 'post_terms', 'scseed_post_terms_shortcode' );
function scseed_post_terms_shortcode( $atts ) {
    $atts = shortcode_atts(
        array(
            'taxonomy' => 'category',
            'sep'      => ', ',
            'links'    => 'true',
        ),
        $atts,
        'post_terms'
    );

    $post_id  = get_the_ID();
    if ( ! $post_id ) {
        return '';
    }
    $taxonomy = sanitize_key( $atts['taxonomy'] );
    if ( ! taxonomy_exists( $taxonomy ) ) {
        return '';
    }
    $terms = get_the_terms( $post_id, $taxonomy );
    if ( is_wp_error( $terms ) || empty( $terms ) ) {
        return '';
    }

    $show_links = ( 'false' !== strtolower( $atts['links'] ) );
    $sep        = wp_kses_post( $atts['sep'] );
    $parts      = array();

    foreach ( $terms as $term ) {
        if ( $show_links ) {
            $url = get_term_link( $term, $taxonomy );
            $parts[] = is_wp_error( $url )
                ? esc_html( $term->name )
                : '<a href="' . esc_url( $url ) . '">' . esc_html( $term->name ) . '</a>';
        } else {
            $parts[] = esc_html( $term->name );
        }
    }
    return implode( $sep, $parts );
}
#cpt#display#shortcode#taxonomy#terms