是否将分类术语作为类名追加到标记中?

时间:2016-11-21 作者:nickpish

我已经为“person”定义了一个自定义的post类型,我想根据与团队名称相对应的分类法将类名附加到输出标记中。例如,如果一个人是“创意”和“互动”团队的一部分,我想输出以下内容:

<div class="person creative interactive">Jane</div>
我发现this thread 在论坛上,但在我的例子中,我需要在echo 语句,因为输出在functions.php 文件

这是我迄今为止提出的一个简化版本,基于上述线程和this Stack Overflow thread:

function display_all_people() {
    // set up arguments for new post query
    $args = array(
        \'post_type\' => \'people\',
        \'order\' => \'ASC\',
        \'orderby\'    => \'meta_value\',
        \'meta_key\'   => \'last_name\'
        );

    $peoplePosts = new WP_Query( $args );
    if ( $peoplePosts->have_posts() ) {
        echo \'<div class="people-listing">\';
        while ( $peoplePosts->have_posts() ) {
            $peoplePosts->the_post();
            $terms = get_the_terms( $post->ID, \'teams\' );

            foreach ($terms as $term) {
                echo \'<div class="person\' . implode(\'\', $term->slug) . \'">\';
            }

            echo \'<div>More markup for each person listing</div>\';
            echo \'</div>\';
        } 
        echo \'</div>\';
    } else {
        return \'<p>Nothing Here.</p>\';
    }
    wp_reset_postdata();
}
因此,我试图使用implode() 连接数组的值(即“团队”分类名称),但它似乎不起作用(PHP正在抛出错误)你知道我如何以这种方式成功地将分类法附加为类名吗?感谢您的帮助。

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

不同的输出,直到集合就绪。

$terms = get_the_terms( $post->ID, \'teams\' );

// create a collection with your default item
$classes = array(\'person\');

foreach ($terms as $term) {

    // add items
    $classes[] = $term->slug;

}

// output all the classes together with a space to separate them.
echo \'<div class="\' . implode(\' \', $classes) . \'">\';

echo \'<div>More markup for each person listing</div>\';
排除忽略添加任何项目:

if( $term->slug !== \'accounting\' ) { $classes[] = $term->slug; }
要清除所有坏苹果:

$pros = array(\'A\', \'B\', \'C\');
$cons = array(\'C\');
$best = array_diff($pros, $cons);
print_r ($best); // A, B
上下文:

$terms = get_the_terms( $post->ID, \'teams\' );

// create a collection with your default item
$classes = array( \'person\' );

if ( $terms && ! is_wp_error( $terms ) ) {
    foreach ( $terms as $term ) {
        $classes[] = $term->slug; // add items
    }
}

// remove any specific classes here
$classes = array_diff( $classes, array( \'creative-services\' ) );

// output all the classes together with a space to separate them.
echo \'<div class="\' . implode( \' \', $classes ) . \'">\';

echo \'<div>More markup for each person listing</div>\';