如何从Wordpress页面/文章中获取所有标签作为简码中的列表?
在每个页面和每篇文章的末尾,我想输出标签作为短代码列表。如何从Wordpress页面/文章中获取所有标签作为简码中的列表?
不幸的是,我对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');
编辑,自从get_the_tags
is_page
已移除的内容只会返回空,如果没有任何
谢谢你的回答!我现在明白了,这就是为什么他之前回到“阵列”。我用你的代码作为shortcode [tagsList]并且输出是空的。无法理解:/ – adifatz
我认为它与@janh提到的is_page检查有关! – webdevdani
将此仅添加到帖子更容易吗? – adifatz
请注意,除非您更改了某些内容,否则页面没有标签。
这就是说,这应该工作。它还在标签周围添加了<ul>
,但您可以更改该标签,并且我确定您会看到它在哪里。我已经使用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');
是否这篇文章你需要什么? https://stackoverflow.com/questions/28202455/wordpress-shortcode-for-tag-list – webdevdani
我试了一下,它返回空 – adifatz