【问题标题】:Wordpress - Add tags as classes? (post_class)Wordpress - 添加标签作为类? (post_class)
【发布时间】:2012-02-27 20:27:10
【问题描述】:

我很惊讶我无法在网上任何地方找到答案,但是有没有办法将帖子的标签添加到课程中?

我正在尝试向 post_class 添加一个过滤器,但它不起作用:

function tag_to_class($classes) {
        global $post;
        foreach((get_the_tags($post->ID)) as $tag)
            $tags[] = $tag->name;
            return $tags;
    }
    add_filter('post_class', 'tag_to_class');
    add_filter('body_class', 'tag_to_class');

我得到错误:

警告:为 foreach() 提供的参数无效

非常感谢任何帮助, 谢谢!

【问题讨论】:

  • 其实标签已经添加到 post_class

标签: php html wordpress tags taxonomy


【解决方案1】:

get_the_tags 必须在 The Loop 中使用,但如果您已经在 The Loop 中,您可以使用the_tags 来获取当前帖子中的标签列表,如下所示:

   <div class="<?php the_tags("", " ", "");?>">

我现在没有可玩的 wordpress,但我想你可以将它们添加到 post_class 像这样:

<div class="<?php post_class(the_tags("", " ", "")); ?>">

【讨论】:

  • 啊。如果我想使用 post_class 函数来添加分类和状态类怎么办?
  • 我之前也遇到过这个问题,但我不记得具体是如何解决的了。我现在没有WP可以玩。我已经更新了我的答案。
【解决方案2】:

这对我有用:

function tags_to_body_class( $classes ) {
    global $post;
    $posttags = get_the_tags( $post->ID );

    if ( $posttags ){
        foreach( $posttags as $tag )
            $tags[] = $tag->slug;
        return $tags;
}
add_filter('body_class', 'tags_to_body_class');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 2013-03-23
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多