Add term list as class

时间:2014-09-05 作者:Justin

我正在尝试添加一个术语列表作为自定义帖子类型的类。

<?php while($portfolio->have_posts()) : $portfolio->the_post(); ?>

                    <?php $categories = get_the_terms($post->ID, \'project_type\');
                        foreach($categories as $category){

                            return $category->name;
                        }
                    ?> 


                    <div class=\'portfolio-tile <?php echo $category ;?>\'>
                        <?php the_post_thumbnail(\'medium\' ); ?>

                    </div>

                <?php endwhile; ?>

                </div>

        <?php wp_reset_query(); ?>

2 个回复
最合适的回答,由SO网友:Justin 整理而成

我发现处理这个问题的最佳方法是利用post\\u类函数并通过该函数添加循环。php文件。这是函数中的代码。php文件:

function term_class($classes){

global $post;

$taxonomies = array(\'project_type\');
$terms = get_the_terms( $post->ID , $taxonomies);

 foreach ($terms as $term) {
    $classes[] = $term->name;
 }

 return $classes;

}

add_filter( \'post_class\', \'term_class\' );
add_filter( \'body_class\', \'term_class\' );
然后我刚刚添加了post\\u class()函数自定义posts模板。谢谢大家的帮助。

SO网友:Chinmoy Kumar Paul

如果您使用return 那么您的循环将无法正常工作。您可以通过以下方式尝试代码:

<?php while($portfolio->have_posts()) : $portfolio->the_post(); ?>

                    <?php $term_class = \'\'; 
                        $categories = get_the_terms($post->ID, \'project_type\');
                        foreach($categories as $category){

                            $term_class .= \' \' . $category->name;
                        }
                    ?> 


                    <div class=\'portfolio-tile <?php echo trim($term_class) ;?>\'>
                        <?php the_post_thumbnail(\'medium\' ); ?>

                    </div>

                <?php endwhile; ?>

                </div>

        <?php wp_reset_query(); ?>

结束

相关推荐