腾讯云服务器优惠活动华纳云香港服务器

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

WordPress主题推荐

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

WordPress获取文章标签函数get_the_tags()的介绍及使用-第1张-boke112百科(boke112.com)

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 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()

本文地址:https://boke112.com/post/2477.html

赞 (0) 打赏
版权声明:本文为原创文章,版权归 boke112百科 所有,欢迎分享本文,转载请保留出处!发布此文是出于传递更多信息之目的,若有来源标注错误或侵犯了您的合法权益,请联系我们,确认后马上更正或删除,谢谢!
wu