【问题标题】:Adding list of classes to PHP array将类列表添加到 PHP 数组
【发布时间】:2013-06-20 20:04:41
【问题描述】:

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

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

【问题讨论】:

  • 你试过打印出数组 $terms 吗?
  • 如果你在循环外使用post_class()函数要小心,你必须提供一个post ID作为第二个参数:http://codex.wordpress.org/Function_Reference/post_class#Display_Posts_Outside_of_the_Loop
  • 我确实打印出 $terms 并得到一个像这样的数组: Array ( [19] => stdClass Object ( [term_id] => 19 [name] => Pendant [slug] => pendant [ term_group] => 0 [term_taxonomy_id] => 19 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 1 [object_id] => 44 ) )
  • @Strategio 我没有看到我的代码有问题...这不会改变任何事情: id ); ?>。请解释一下?
  • 在 foreach 循环之后有一个额外的“}”,并且在编写 html 之前没有关闭“?>” php。您应该启用 php display_errors。

标签: php wordpress loops foreach


【解决方案1】:

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

【讨论】:

  • 你应该在循环之前添加 $cats 数组。
  • 你的意思是定义 $cats = array();在顶部?
  • 使用内爆有效吗?现在我认真地认为问题出在别的地方。可能 html 中的类名之间需要一个空格。
猜你喜欢
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 2012-08-30
  • 2016-10-16
相关资源
最近更新 更多