dsfew215211 2014-03-31 21:15
浏览 47
已采纳

如何在Wordpress页面上使用get_the_tags?

I've added tags to my Wordpress pages (which are working fine) but I'm trying to list them on the page.

The idea is to get all the tags a particular page (not post) has and format them. What I'm getting is either 2 random (unrelated) tags, or the entire tag list. I'm not sure what I'm missing here.

$relatedArea = the_slug(false); //gets the slug of the page - false represses the echo statement

$allTags = get_tags(); //gets all the tags
$areasOfLaw = array(); //starts the array

// check if the tag is included on the page
foreach ($allTags as $tag) {
  if(has_tag($relatedArea)) {
    $areasOfLaw[] = $tag; //add to the array
  }
}

Tried $areasOfLaw = get_the_tags() but it gave me random tags.

Here's the formatting, but I'm pretty sure it's working correctly.

foreach($areasOfLaw as $tag){
    echo '
        <a href="'.get_site_url().'/services/'.$tag->slug.'">
        <li>'.$tag->name.'
        <span class="glyphicon glyphicon-chevron-right pull-right action"></span>
        </li></a>';
    }

edit: this is my tag support included in the functions file

// add tag support to pages
function tags_support_all() {
    register_taxonomy_for_object_type('post_tag', 'page');
}

// ensure all tags are included in queries
function tags_support_query($wp_query) {
    if ($wp_query->get('tag')) $wp_query->set('post_type', 'any');
}

// tag hooks
add_action('init', 'tags_support_all');
add_action('pre_get_posts', 'tags_support_query');
  • 写回答

2条回答 默认 最新

  • duan1979768678 2014-03-31 21:58
    关注

    The get_the_tags() function returns all the tags associated with a post and if you use it inside the loop then you may use it like this:

    $tags = get_the_tags();
    

    But if you use it outside of the loop then you have to supply the ID of the post for which you want to retrieve that tags, for example to get all the tags of post whose ID is 10:

    $tags = get_the_tags(10);
    

    Now you can loop $tags like this:

    foreach($tags as $tag)
    {
        echo $tag->name . ' ';
    }
    

    Read more on Codex.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥200 csgo2的viewmatrix值是否还有别的获取方式
  • ¥15 Stable Diffusion,用Ebsynth utility在视频选帧图重绘,第一步报错,蒙版和帧图没法生成,怎么处理啊
  • ¥15 请把下列每一行代码完整地读懂并注释出来
  • ¥15 pycharm运行main文件,显示没有conda环境
  • ¥15 寻找公式识别开发,自动识别整页文档、图像公式的软件
  • ¥15 为什么eclipse不能再下载了?
  • ¥15 编辑cmake lists 明明写了project项目名,但是还是报错怎么回事
  • ¥15 关于#计算机视觉#的问题:求一份高质量桥梁多病害数据集
  • ¥15 特定网页无法访问,已排除网页问题
  • ¥50 如何将脑的图像投影到颅骨上