将类列表添加到PHP数组

将类列表添加到PHP数组,php,wordpress,loops,foreach,Php,Wordpress,Loops,Foreach,我想使用php循环一个产品类别,并将它们存储到一个数组中,数组将被分配为每个产品的类名。由于某些原因,我的代码无法工作,并且没有PHP错误。也许这是一个wordpress问题: $classes = array(); $terms = get_the_terms($post->ID, 'product_cat'); foreach ($terms as $term) { $classes[] = $term->slug; } <li <?php post_cl

我想使用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 ); ?>>
$classes=array();
$terms=get_the_terms($post->ID,'product_cat');
foreach($terms作为$term){
$classes[]=$term->slug;
}

使用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); ?>>
>

您是否尝试打印出数组$terms?如果在循环之外使用
post_class()
函数,请小心,您必须提供一个post ID作为第二个参数:。我确实打印出了$terms并得到如下数组:数组([19]=>stdClass对象([term_ID]=>19[name]=>Pendant[slug]=>Pendant[term_group]=>0[term_taxonomy_id]=>19[taxonomy]=>product_cat[description]=>0[count]=>1[object_id]=>44]@Strategio我看不到我的代码有什么问题……这并没有改变一件事:。请解释一下?在foreach循环之后有一个额外的“}”,并且没有关闭“>”在编写html之前使用php。您应该启用php显示错误。您应该在循环之前添加$cats数组。您的意思是只在顶部定义$cats=array();使用内爆工作?现在我认真地认为问题出在其他方面。html中的类名之间可能需要一个空格。