我想显示按属性过滤的相关产品,该属性应等于页面cookie中的值。
我编辑related.php模板,如下所示:
<?php woocommerce_product_loop_start(); ?>
<?php foreach ( $related_products as $related_product ) :
// extract attribute filter_location in an array
$results = $related_product->get_attribute( 'pa_filter_location' );
// extract value from cookies filter_location
$fl = $_COOKIE['filter_location'];
foreach ( $results as $key ) {
if( $key == $fl ) {
$post_object = get_post( $related_product->get_id() );
setup_postdata( $GLOBALS['post'] =& $post_object );
wc_get_template_part( 'content', 'product' );
}
}
endforeach; ?>
<?php woocommerce_product_loop_end(); ?>
但是我得到了错误:警告:
为foreach()提供的参数无效
可能是什么问题?
答案 0 :(得分:3)
问题来自此行:
$results = $related_product->get_attribute( 'pa_filter_location' );
这不是给出数组,而是用逗号分隔的术语字符串。因此,您不能以这种方式在foreach循环中使用它。
请使用以下重新访问的代码:
<?php woocommerce_product_loop_start(); ?>
<?php foreach ( $related_products as $related_product ) :
// extract attribute filter_location in an array
$terms = $related_product->get_attribute( 'pa_filter_location' );
// Set each term in an array
$terms = ! empty($terms) ? (array) explode(', ', $terms) : array();
foreach ( $terms as $term ) {
if( isset($_COOKIE['filter_location']) && $term == $_COOKIE['filter_location'] ) {
$post_object = get_post( $related_product->get_id() );
setup_postdata( $GLOBALS['post'] =& $post_object );
wc_get_template_part( 'content', 'product' );
}
}
endforeach; ?>
<?php woocommerce_product_loop_end(); ?>
它应该彻底解决与foreach循环有关的错误。