Npcink Blog
切换菜单
本页目录2 节

在开发插件的 SEO 功能时有这个需求,需要获取当前文章不带超级链接的标签,这一节的 WordPress 开发教程就来学习下怎么获取不带链接的标签吧。

  • 参考来源:ztmao.com/jiaocheng/2775.html

背景图片

核心代码:

function tagtext(){ global $post; $gettags = get_the_tags($post->ID); if ($gettags) { foreach ($gettags as $tag) { $posttag[] = $tag->name; } $tags = implode( ',', $posttag ); echo $tags; } }

在要显示纯文本标签的地方添加以下调用代码:

<?php tagtext();?>

如果只是需要获取第一个纯文本标签:

<?php
$posttags = get_the_tags();
$count=0;
if ($posttags) {
foreach($posttags as $tag) {
$count++;
if (1 == $count) {
echo $tag->name . '|';
}
}
}
?>

下面的代码也可以获取文章第一个标签(纯文本):

<?php
$tag = get_the_tags($id);
if ($tag) {
$tag = $tag[0];
echo $tag->name;
}
?>

如果希望获取 WordPress 的第一个标签链接(带链接):

//文章第一个tag
function first_tag_link()
{
if ( $posttags = get_the_tags() )
{
$tag = current( $posttags );
printf(
'<a href="%1$s"><span>%2$s</span></a>',
get_tag_link( $tag->term_id ),
esc_html( $tag->name )
);
}
}

用法:

<?php first_tag_link(); ?>

怎么在日志循环外获取日志的 ID 呢?来看看这篇 WordPress 开发教程吧。