【问题标题】:How to get all tags from Wordpress page/post as a list in shortcode?如何从 Wordpress 页面/帖子中获取所有标签作为简码列表?
【发布时间】:2018-04-16 17:22:27
【问题描述】:

在每个页面和每个帖子的末尾,我想将标签输出为简码列表。

很遗憾,我对 PHP 了解不多,但是懂的人一定能用下面的代码纠正我的错误。

提前谢谢你!

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

【问题讨论】:

标签: php html wordpress shortcode


【解决方案1】:

该方法需要返回一个字符串才能打印任何标记。

“短代码函数应返回用于替换短代码的文本。” 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');

编辑:删除了对 is_page 的检查,因为如果没有,get_the_tags 将简单地返回空

【讨论】:

  • 谢谢你的回答!我现在明白了,这就是他之前返回“Array”的原因。我将您的代码用作简码 [tagsList] 并且输出为空。想不通:/
  • 我认为这与@janh 提到的 is_page 检查有关!
  • 只在帖子中添加这个更容易吗?
  • get_the_tags() 将默认为循环中的当前帖子(它应该是,因为在 the_content 过滤器上解析短代码)。但是,如有必要,请确保在函数中使用之前添加global $post;
  • 成功了! “全球 $post;”不见了...非常感谢!
【解决方案2】:

请注意,除非您更改了某些内容,否则页面没有标签。

也就是说,这应该可行。它还在标签周围添加了&lt;ul&gt;,但您可以更改它,我相信您会看到在哪里。我使用了is_singular,但你可能根本没有这种情况,除非你在自定义帖子类型中添加[tags],并且不希望在那里输出。 我假设您想添加更多修改,否则 webdevdani 关于使用 the_tags 的建议可能更简单。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    • 2020-04-09
    • 1970-01-01
    相关资源
    最近更新 更多