Skip to content
Advertisement

How to get all tags from WordPress page/post as a list in shortcode?

At the end of each page and every post, I would like to output the tags as a list in a shortcode.

Unfortunately, I do not know much about PHP, but someone who can understand will definitely be able to correct my mistake using the code below.

Thank you in advance!

<?php // functions.php | get tags
function addTag( $classes = '' ) {

    if( is_page() ) {
        $tags = get_the_tags(); // tags
        if(!empty($tags))
        {
            foreach( $tags as $tag ) {
                $tagOutput[] = '<li>' . $tag->name . '</li>';
            }
        }
    }
    return $tags;

}
add_shortcode('tags', 'addTag');

Advertisement

Answer

The method needs to return a string to be able to print any markup.

“Shortcode functions should return the text that is to be used to replace the shortcode.” https://codex.wordpress.org/Function_Reference/add_shortcode

function getTagList($classes = '') {
    global $post;
    $tags = get_the_tags($post->ID);
    $tagOutput = [];

    if (!empty($tags)) {
        array_push($tagOutput, '<ul class="tag-list '.$classes.'">');
        foreach($tags as $tag) {
            array_push($tagOutput, '<li>'.$tag->name.'</li>');
        }
        array_push($tagOutput, '</ul>');
    }

    return implode('', $tagOutput);
}

add_shortcode('tagsList', 'getTagList');

Edit: Removed check for is_page since get_the_tags will simply return empty if there aren’t any

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement