admin管理员组

文章数量:1122826

Taxonomy name is "intro". I'm inside a shortcode so I dont need to echo.I need a variable for the selected taxonomy term to put in the return. What I do has no effect

$terms2 = wp_get_post_terms($post->ID,'intro',array('fields' => 'names'));

Taxonomy name is "intro". I'm inside a shortcode so I dont need to echo.I need a variable for the selected taxonomy term to put in the return. What I do has no effect

$terms2 = wp_get_post_terms($post->ID,'intro',array('fields' => 'names'));
Share Improve this question asked Mar 30, 2024 at 9:42 Andrea SacconiAndrea Sacconi 797 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

This is the solution:

$term_name = get_the_terms(get_the_ID(), 'intro')[0]->name;

If you want to retrieve the selected term of a custom taxonomy called "intro" for a particular post inside a shortcode, you can use the wp_get_post_terms() function to fetch the terms associated with that post

function my_custom_shortcode_function() {
    global $post;
    
    // Get the terms for the "intro" taxonomy associated with the current post
    $terms = wp_get_post_terms($post->ID, 'intro', array('fields' => 'names'));

    // Check if any terms are retrieved
    if (!empty($terms)) {
        // Assuming you want to use the first term only
        $selected_term = $terms[0];
    } else {
        // If no terms are retrieved, set a default value or handle the case as needed
        $selected_term = 'No Term Selected';
    }

    // Now you can use $selected_term as needed
    return $selected_term;
}
add_shortcode('my_shortcode', 'my_custom_shortcode_function');

本文标签: phphow can I get the selected term of a custom taxonomy