wordpress想实现调用文章的tags标签作为文章页面的keywords,可由于标签调用函数默认带超链接,因此使用其作为文章页面的关键词前需去掉超链接变身为纯文本,否则页面会出现错位等情况。wordpress调用不带超链接的tag标签的方法已有人公布,通过wordpress强大的functions.php文件即可实现。
调用纯文本Tag标签:
在当前WordPress主题的functions.php文件中添加以下函数代码(所有标签,用英文逗号分割):
1 | function tagtext(){ global $post; $gettags = get_the_tags($post->ID); if ($gettags) { foreach ($gettags as $tag) { $posttag[] = $tag->name; } $tags = implode( ',', $posttag ); echo $tags; } } |
在要显示纯文本标签的地方添加以下调用代码:
1 | <?php tagtext();?> |
如果只是需要获取第一个纯文本标签:
1 2 3 4 5 6 7 8 9 10 11 12 | <?php $posttags = get_the_tags(); $count=0; if ($posttags) { foreach($posttags as $tag) { $count++; if (1 == $count) { echo $tag->name . '|'; } } } ?> |
下面的代码也可以获取文章第一个标签(纯文本):
1 2 3 4 5 6 7 | <?php $tag = get_the_tags($id); if ($tag) { $tag = $tag[0]; echo $tag->name; } ?> |
如果希望获取wordpress的第一个标签链接(带链接):
1 2 3 4 5 6 7 8 9 10 11 12 13 | //文章第一个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 ) ); } } |
示例:
1 | <?php first_tag_link(); ?> |