skip to Main Content

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

2

Answers


  1. 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' );
    
    Login or Signup to reply.
  2. 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' );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search