Hi!请登陆

如何在WordPress当前标签页获取标签ID?

2021-1-5 55 1/5

因为 WordPress 没有内置这样的函数,所以,我们要自定义一个这样的函数,将下面这段代码放到主题的 functions.php 文件中:

  1. //获得当前 TAG 标签 ID
  2. function get_current_tag_id() {
  3.     $current_tag = single_tag_title('', false);//获得当前 TAG 标签名称
  4.     $tags = get_tags();//获得所有 TAG 标签信息的数组
  5.     foreach($tags as $tag) {
  6.         if($tag->name == $current_tagreturn $tag->term_id; //获得当前 TAG 标签 ID,其中 term_id 就是 tag ID
  7.     }
  8. }

上面的代码就是一个获取当前标签页标签 ID 号的函数,然后,我们只要在需要标签 ID 的地方调用这个函数就可以了。

  1. <?php echo get_current_tag_id(); ?>

上面这句是直接显示标签 ID 号,也可以直接将函数的返回值赋于一个变量,如下:

  1. <?php $tag = get_current_tag_id(); ?>

就可以在需要的地方直接调用这个 $tag 变量就可以了。

内容整理自:高时银博客 - http://wanlimm.com/77201505274116.html

相关推荐