在wordpress主题开发中,想在标签文章列表页面获取当前标签的ID、别名怎么办?可以通过标签名称使用get_term_by()函数来实现,get_term_by()函数可以返回分类或标签的名称、别名和ID等信息。

1
2
3
4
5
if(is_tag()){
	$tagName = single_tag_title(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\',false);
	$tagObject = get_term_by(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'name\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\',$tagName,\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'post_tag\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\');
	$tagID = $tagObject->term_id;
}

代码意思:在标签页面,选择获取当前标签页面的标签名称,使用该标签名称通过get_term_by()函数返回一个数组值,然后就可以获取数组中当前标签的ID了。

扩展:

也可以写成函数放在主题的functions.php文件(以下代码二选一)

代码一:

1
2
3
4
5
6
7
8
9
function get_tag_id() {
	$tagname = single_tag_title(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\',false);
	$tag = get_term_by(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'name\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\', $tagname, \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'post_tag\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\');
	if($tag){
		return $tag->term_id;
	}else{
		return 0;
	}
}

代码二:

1
2
3
4
5
6
7
function get_tag_id() {
 $current_tag = single_tag_title(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\', false);
 $tags = get_tags();
 foreach($tags as $tag) {
  if($tag->name == $current_tag) return $tag->term_id;
 }
}

调用代码:

1
<?php echo get_tag_id();?>

相关新闻

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

联系我们

联系我们

151-1101-0018

在线咨询:
邮件:30115776@qq.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信
关注微信
分享本页
返回顶部