【问题标题】:How do I use get_the_tags on a Wordpress page?如何在 Wordpress 页面上使用 get_the_tags?
【发布时间】:2014-03-31 21:15:23
【问题描述】:

我已将标签添加到我的 Wordpress 页面(工作正常),但我正在尝试在页面上列出它们。

这个想法是获取特定页面(不是帖子)具有的所有标签并格式化它们。我得到的是 2 个随机(不相关)标签或整个标签列表。我不确定我在这里缺少什么。

$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
  }
}

试过$areasOfLaw = get_the_tags(),但它给了我随机标签。

这是格式,但我很确定它工作正常。

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>';
    }

编辑:这是函数文件中包含的我的标签支持

// 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');

【问题讨论】:

  • 你是如何在循环内使用get_the_tags()函数的?
  • 我一直使用它作为$areasOfLaw = get_the_tags();,但它没有返回我想要的东西

标签: php wordpress tags


【解决方案1】:

get_the_tags() 函数返回与post 关联的所有标签,如果你在循环中使用它,那么你可以像这样使用它:

$tags = get_the_tags();

但是如果你在循环之外使用它,那么你必须提供你想要检索该标签的帖子的ID,例如获取ID10的帖子的所有标签:

$tags = get_the_tags(10);

现在你可以像这样循环$tags

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

阅读更多关于Codex

【讨论】:

  • 嗯。我在循环中,但无论出于何种原因,ID 都没有正确传递。当我使用get_the_tags(46)(例如)时,我得到了正确的标签。使用 the_ID() 返回 1,即使页面为 46。这帮助我找到了解决方案:我的 id 没有被正确返回。
  • 如果您在循环中(post 的循环),那么您可以使用get_the_tags($post-&gt;ID) 明确设置当前帖子的ID
【解决方案2】:

@Sheikh Heera 为我指明了正确的方向。

结果即使$areasOfLaw 在循环中,我的页面 id 也没有正确返回。

这是对我有用的代码:

$page_object = get_queried_object();
$page_id = get_queried_object_id();
$areasOfLaw = get_the_tags($page_id);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 2013-05-14
    • 2021-01-10
    • 1970-01-01
    • 2013-02-19
    相关资源
    最近更新 更多