在WooCommerce中使用第二个foreach循环将列表值列为单个<li>元素

时间:2017-06-23 09:26:20

标签: php wordpress woocommerce attributes product

我正在尝试将产品属性(仅限选定的)显示为列表,如下面的第一张图片所示:

screenshot of how the list should look

很遗憾,我的列表目前看起来像这样: (我如何将这些值除以另一个foreach语句?)

enter image description here

此外,我的代码/短代码显示了所有找到的产品属性,并希望使用类似:[product_attributes:sizes | color | print]来仅选择我想要显示的属性。

add_filter( 'wplister_process_template_html', 'my_wplister_template_filter_product_attributes_list', 10, 3 );
function my_wplister_template_filter_product_attributes_list( $html, $item, $images ) {

    $post_id    = $item['parent_id'] ? $item['parent_id'] : $item['post_id'];
    $attributes = ProductWrapper::getAttributes( $post_id );

    $attributes_list = '';
    foreach ($attributes as $name => $value) {
        $value           = '<li>' . str_replace( '|', ', ', $value ) . '</li>';
        $attributes_list .= '<div>';
        $attributes_list .= '<p>' . $name . ': <p>';
        $attributes_list .= '<ul class="variation">' . $value . '</ul>';
        $attributes_list .= '</ul>';
        $attributes_list .= '</div>';   
    }

    $html = str_replace( '[[product_attributes_list]]', $attributes_list, $html );
    return $html;
}

如何将列表值中的第二个foreach循环用作单个<li>元素?

由于

1 个答案:

答案 0 :(得分:1)

我无法真正测试它。我在代码中进行了一些更改,以进行第二次foreach循环。

试试这个:

add_filter( 'wplister_process_template_html', 'my_wplister_template_filter_product_attributes_list', 10, 3 );
function my_wplister_template_filter_product_attributes_list( $html, $item, $images ) {

    $post_id    = $item['parent_id'] ? $item['parent_id'] : $item['post_id'];
    $attributes = ProductWrapper::getAttributes( $post_id );

    $attributes_list = '';
    foreach ($attributes as $name => $attr_values) {

        $attributes_list .= '<div>
        <p>' . $name . ': <p>
        <ul class="variation">';

        // Dispaching each attribute values in an array
        $attr_values_arr = explode( '|', $attr_values );

        // The second foreach loop
        foreach ($attr_values_arr as $attr_value){
            $attributes_list .= '<li>' . $attr_value . '</li>';
        }

        $attributes_list .= '</ul>
        </div>';
    }

    $html = str_replace( '[[product_attributes_list]]', $attributes_list, $html );

    return $html;
}

代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中。

我希望这会奏效。