0

我想使用 php 遍历产品类别并将它们存储到一个数组中,该数组将被分配为每个产品的类名。由于某种原因,我的代码无法正常工作,并且没有 PHP 错误。也许这是一个wordpress问题:

$classes = array();

$terms = get_the_terms($post->ID, 'product_cat');
foreach ($terms as $term) {
    $classes[] = $term->slug;
}

<li <?php post_class( $classes ); ?>>

本质上,我试图将类别作为类名分配给它们各自的产品。这不会引发错误,但不会加载任何内容。有人在这里看到任何问题吗?

4

1 回答 1

0

使用 array_shift 分解数组对我有用,但如果 $cats 有多个类,它就不起作用

<?php $classes = array();
$terms = get_the_terms($post->ID, 'product_cat'); 

foreach ($terms as $term) {
        $cats[] = $term->slug;
}

$classes[] = implode(" ", $cats);

<li <?php post_class( $classes); ?>>
于 2013-06-20T20:24:30.353 回答