phpwordpressshortcodetaxonomytaxonomy-terms

Displaying taxonomy name in single post template of cpt


I'll start by saying that I have no background in php.

I need to embed a shortcode to display the name of the specific taxonomy the post is associated with.

The shortcode is embedded in a single post template.

Remarks:

  1. I don't need a link to the taxonomy.
  2. how can i embedded it as a shortcode?

I would appreciate your help


Solution

  • If you want show only one taxonomy you can try this following version of code.

    function display_post_single_tax_terms( $atts ) {
        // Get post ID
        $post_id = get_the_ID();
    
        // Check if post ID exists
        if ( $post_id ) {
            // Get taxonomy terms associated with the post
            $terms = get_the_terms( $post_id, 'your_taxonomy_name' ); // Replace 'your_taxonomy_name' with the name of your taxonomy
    
            // Check if terms exist
            if ( $terms && ! is_wp_error( $terms ) ) {
                return $terms[0]->name; // you can wrap this with any tag if you want;
            }
        }
    
        return ''; // Return empty string if no taxonomy terms found
    }
    add_shortcode( 'display_post_taxonomy', 'display_post_single_tax_terms' );