0

I've got a useful snippet of code to create a shortcode and display post tags and their descriptions on posts. I'm trying to display all tags assigned to the particular live post, not all tags for the site etc.

if i use echo the term/description end up displaying at the top of the content rather than within the element where the shortcode is; and if I use return only the first tag is displayed and other tags are ignored.

A solution would be greatly appreciated. thanks

function returnpost_tags() {
     return get_the_tag_list( '', ', ', '' );
}
add_shortcode( 'post-tags', 'returnpost_tags' );

function returnpost_tagsdesc() {
    // get tags by post ID 
    $post_ID = get_the_ID();

    // here, you can add any custom tag
    $terms = get_the_terms( $post_ID , 'post_tag', array( "description" => "ids" ) );

    foreach ( $terms as $term ) {
        // The $term is an object, so we don't need to specify the $taxonomy.
        $term_link = get_term_link( $term );
        $term_ID = $term->term_id;

        // If there was an error, continue to the next term.
        if ( is_wp_error( $term_link ) ) {
                continue;
        }

        //echo '' . $term->name . '';
        return term_description($term_ID);

        // another option
        // echo  '<p>' . $term->description . '</p>';
    }
}
add_shortcode( 'post-tags-desc', 'returnpost_tagsdesc' );
0

You need to store every tags in a variable, and then return the whole thing. Define an empty value before the foreach and append the data to it. Don't use the return inside the loop, since it will quit the loop once it reaches the first return. Take a look at this piece of your code that I have modified:

// Define an empty variable
$data = '';
foreach ( $terms as $term ) {
    // The $term is an object, so we don't need to specify the $taxonomy.
    $term_link = get_term_link( $term );
    $term_ID = $term->term_id;

    // If there was an error, continue to the next term.
    if ( is_wp_error( $term_link ) ) {
            continue;
    }

    // Append each term's description to it
    $data .= term_description($term_ID);

}
// Return the entire data
return $data;
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.