anat
anat

Reputation: 5

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

Upvotes: 0

Views: 63

Answers (2)

Noman
Noman

Reputation: 58

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' );

Upvotes: 0

Noman
Noman

Reputation: 58

Please try the following code to fetch all the taxonomies associated with post.

make sure you're receiving the proper post ID and correct taxonomy name, so you may need a little bit of debugging, please let me know if you're facing any issues. I'll be happy to help further.

function display_post_taxonomy_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 ) ) {
            $taxonomy_list = '<ul>';
            foreach ( $terms as $term ) {
                $taxonomy_list .= '<li><a href="' . esc_url( get_term_link( $term ) ) . '">' . esc_html( $term->name ) . '</a></li>';
            }
            $taxonomy_list .= '</ul>';

            return $taxonomy_list;
        }
    }

    return ''; // Return empty string if no taxonomy terms found
}
add_shortcode( 'display_post_taxonomy', 'display_post_taxonomy_terms' );

Upvotes: 0

Related Questions