简体   繁体   中英

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

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

Be aware that pages don't have tags unless you've changed something.

That said, this should work. It also adds the <ul> around the tags, but you can change that, and I'm sure you see where. I've used is_singular , but you'll probably get away without that condition at all, unless you do add [tags] in a custom post type and don't want the output there. I assume you want to add more modification, otherwise webdevdani's suggestion regarding using the_tags is probably simpler.

// get tags 
function addTag( $classes = '' ) {
    if( is_singular("post") || is_singular("page") ) {
        $tags = get_the_tags();
        if(is_array($tags) && !empty($tags)) {
            $tagOutput = array("<ul>");
            foreach( $tags as $tag ) {
                $tagOutput[] = '<li>' . $tag->name . '</li>';
            }
            $tagOutput[] = "</ul>";
            return implode("", $tagOutput);
        }
    }
    return "";
}
add_shortcode('tags', 'addTag');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM