WordPress获取文章标签函数get_the_tags()的介绍及如何使用

一天,当你走过蔓草荒烟,我便在那里向你轻声呼喊,以风声,以水响。斩断自己的退路,才能更好地赢得出路。

平时我们在编辑文章的时候都喜欢顺手添加上 1 个或多个标签(PS:想实现自动添加标签请参考『WordPress 纯代码实现自动为文章添加标签及标签内链接』),那么应该如何获取某篇文章的所有标签呢?这就需要用到 get_the_tags()函数了,这个函数就是今天的重点内容。

get_the_tags()函数介绍

检索(获取)当前文章的标签。

get_the_tags( int $post_id )

参数:

$post_id(int):(必填)文章的 ID。

返回:

(array | false | WP_Error)有标签则返回标签对象数组,没有则返回 false。

函数所在文件:wp-includes/category-template.php

function get_the_tags( $post_id = 0 ) {
$terms = get_the_terms( $post_id, 'post_tag' );
return apply_filters( 'get_the_tags', $terms );
}

get_the_tags()函数使用示例

示例:输出当前文章第一个标签

$post_tags = get_the_tags();
if ( $post_tags ) {
echo $post_tags[0]->name; 
}

示例:输出当前文章所有标签

$post_tags = get_the_tags();
if ( $post_tags ) {
foreach( $post_tags as $tag ) {
echo $tag->name . ', '; 
}
}

示例:显示带有链接和自定义分隔符的文章标签

function show_tags()
{
$post_tags = get_the_tags();
$separator = ' | ';
if (!empty($post_tags)) {
foreach ($post_tags as $tag) {
$output .= '<a rel="nofollow noopener noreferrer" href="' . get_tag_link($tag->term_id) . '">' . $tag->name . '</a>' . $separator;
}
return trim($output, $separator);
}
}

示例:在下拉列表中显示文章的标签

<?php
function dropdown_tags(){
echo '<select name="tag" id="tag" class="postform">';
foreach ( get_the_tags() as $tag ) {
echo '<option value="' . $tag->name . '">' . $tag->name . "</option>\n";
}
echo '</select>';
}
?>
<h2><?php _e( 'Tags:', 'textdomain' ); ?></h2>
<form id="tags-select" class="tags-select" action="<?php echo esc_url( home_url( '/' ) ); ?>" method="get">
<?php dropdown_tags(); ?>
<input type="submit" name="submit" value="view" />
</form>

以上内容整理自@WordPress - get_the_tags()

以上就是WordPress获取文章标签函数get_the_tags()的介绍及如何使用。青春就像是切洋葱,咱们都泪流满面,却还乐此不疲。更多关于WordPress获取文章标签函数get_the_tags()的介绍及如何使用请关注haodaima.com其它相关文章!

您可能有感兴趣的文章
WordPress站点Gravatar头像前后台不显示的如何解决办法

WordPress做公司官网好吗?会不会显得档次很低?

WordPress主题需要支持https吗?WordPress站点如何如何实现https?

WordPress站点的页面/标签/分类URL地址如何添加.html?

WordPress站点更换了域名后数据库应该如何操作替换新旧域名?