Skip to content

Instantly share code, notes, and snippets.

@AchalJ
Created June 19, 2020 09:30
Show Gist options
  • Save AchalJ/8ea00a4cd06dcb77eaace119b138fa97 to your computer and use it in GitHub Desktop.
Save AchalJ/8ea00a4cd06dcb77eaace119b138fa97 to your computer and use it in GitHub Desktop.
Shortcode to get current post terms in HTML | WordPress
add_shortcode('get_current_post_terms', function( $atts ) {
$atts = shortcode_atts( array(
'taxonomy' => 'category',
'limit' => '1',
'fields' => 'slugs',
'separator' => ',',
'print' => 0
), $atts );
global $post;
$slugs = array();
if ( $post ) {
$slugs = wp_get_post_terms( $post->ID, $atts['taxonomy'], array(
'number' => intval( $atts['limit'] ),
'fields' => sanitize_text_field( $atts['fields'] )
) );
}
if ( ! is_wp_error( $slugs ) && ! empty( $slugs ) ) {
$terms = implode( $atts['separator'], $slugs );
if ( $atts['print'] ) {
echo $terms;
} else {
return $terms;
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment