php - 如何从 WordPress 页面/帖子中获取所有标签作为短代码列表?

标签 php html wordpress shortcode

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

不幸的是,我对 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');

最佳答案

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

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

关于php - 如何从 WordPress 页面/帖子中获取所有标签作为短代码列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47104890/

相关文章:

php - 当没有发生数据库异常时,Laravel 事务不会回滚

php - 在执行 PHP 单元测试期间如何在 CLI 中输出?

php - 通过另一个数组对数组进行分组?

html - 如何将 div 放在悬停上方而不被删除

sql - 针对旧帖子列表优化 WordPress SQL 查询

php - mysql查询只返回一个字的字符串

php - 在 PHP 中添加 <sup> 不起作用

php - Mysql 上的多维数组重复数据存储

html - 如何移除 box-shadow 提供的边框?

javascript - 自定义 jQuery 不适用于 Wordpress Ninja Forms 插件