在每个页面和每个帖子的末尾,我想将标签输出为短代码中的列表。
不幸的是,我对 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/