【问题标题】:Unable to get get_the_tags() in Wordpress Template无法在 Wordpress 模板中获取 get_the_tags()
【发布时间】:2009-05-19 03:27:32
【问题描述】:

我正在使用此代码在我的 wordpress 帖子中获取主题的标签

`<?php
$posttags = get_the_tags();
if ($posttags) {
  foreach ($posttags as $tag) {
     $tagnames[count($tagnames)] = $tag->name;
  }
  $comma_separated_tagnames = implode(", ", $tagnames);
  print_r($comma_separated_tagnames);
}
?>`

问题是它返回“所有帖子”的标签,而不仅仅是单个帖子,我认为问题是如果帖子没有标签 - 它只是插入标签。

谁能帮忙修改一下:

  1. 它只为帖子返回标签 - 不是所有标签
  2. 如果帖子没有标签,则不要返回任何内容

附注-Can check out here for the wordpress docs

【问题讨论】:

  • 请不要转发问题。 stackoverflow.com/questions/880673/…
  • 再次感谢您的回复-当我使用此代码时,我面临的问题是标签是“聚合的”,即它在顶部帖子上打印标签很好-只出现顶部帖子标签,但随后在第二个帖子中 - 它打印顶部帖子标签和第二个帖子标签,依此类推。第三篇文章、第 1 篇、第 2 篇和第 3 篇文章标签等如何限制此代码中的标签,只显示一篇文章? – 安迪 46 分钟前
  • 即这段代码完美运行 name . ' '; } } ?> 它只返回每个帖子的标签。你的工作很好 - 因为我可以在 echo 中打印 $comma_separate_tagnames - 但我不是 PHP 编码器,所以不知道如何更改代码以不“计数/聚合”标签 - 而是只显示每个帖子的标签– 安迪 19 分钟前

标签: wordpress wordpress-theming


【解决方案1】:
<footer class="entry-footer">
                    <?php //get all tags for the post
                    $t = wp_get_post_tags($post->ID);
                    echo "<p class='tags-list'>TAGGED WITH: ";
                    foreach ($t as $tag) {
                        $tag_link = get_tag_link($tag->term_id);
                    echo "<a href='$tag_link' class='used-tag' rel='tag'>".($tag->name)."</a>&nbsp;";
                    }
                    echo "</p>";
                    ?>
                    </footer>

这就是我所做的,在循环中显示每个帖子的标签。

【讨论】:

    【解决方案2】:

    尝试使用:

    <?php the_tags(); ?>
    

    在“Loop”内。

    Function Reference

    【讨论】:

    • the_tags();将迫使您回显标签及其链接,在这种情况下,开发人员只需要单独的标签名称或标签链接。
    【解决方案3】:

    好吧,我希望这可以帮助某人,我在这个问题上停留了大约一个小时 试图获取我的帖子的标签“这样我就可以将它与 twitter 分享链接混合” the_tags();函数没用,因为我在 WP 循环 get_the_tag_list() 之外使用它;对我来说很完美,因为它可以包含帖子 ID,

    $postid = $wp_query->post->ID; 
    
    $posttags =  strip_tags( get_the_tag_list( ' ', '', '', "$postid" ) ) ;
    

    ^^ 上面的代码我剥离了 html 代码以获取没有 href 链接的标签名称。

    这是函数用例:-

    get_the_tag_list( string $before = '', string $sep = '', string $after = '', int $id )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-18
      • 2017-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多