我正在尝试显示当前产品的属性。在下面的屏幕截图中,我声明了属性“白酒品牌”,并为其分配了多个值:
以下是我目前正在编写的代码:
<?php
$liquor = new WP_Query( array(
\'post_type\' => \'product\',
\'product_cat\' => \'liquors\',
\'meta_query\' => array(
array(
\'key\' => \'_stock_status\',
\'value\' => \'instock\'
)
)
) );
if ( $liquor->have_posts() ) : while ( $liquor->have_posts() ) : $liquor->the_post();
?>
<?php
$liquor_brands = get_terms(\'pa_liquor-brands\');
foreach ( $liquor_brands as $liquor_brand ) :
?>
<?php endforeach; ?>
<div id="post-<?php the_ID(); ?>" class="three columns product-post">
<?php echo $liquor_brand->slug ?>
</div>
<?php wp_reset_postdata(); ?>
<?php endwhile; else: ?>
<?php //error message ?>
<?php endif; ?>
<?php wp_reset_query(); ?>
这是输出的屏幕截图。它只显示我设置的最后一个值,即“非常老的鲁姆船长”:
最合适的回答,由SO网友:Dave Romsey 整理而成
您正在初始化$liquor_brands
数组,通过foreach
什么都不做的循环,然后发出$liquor_brand
在foreach
环$liquor_brand
将设置为$liquor_brands
因为整个数组被迭代。长话短说,你应该在foreach
回路:
<?php
$liquor = new WP_Query( array(
\'post_type\' => \'product\',
\'product_cat\' => \'liquors\',
\'meta_query\' => array(
array(
\'key\' => \'_stock_status\',
\'value\' => \'instock\'
)
)
) );
if ( $liquor->have_posts() ) : while ( $liquor->have_posts() ) : $liquor->the_post(); ?>
<div id="post-<?php the_ID(); ?>" class="three columns product-post">
<?php
$liquor_brands = get_terms( \'pa_liquor-brands\' );
foreach ( $liquor_brands as $liquor_brand ) {
echo $liquor_brand->slug . \' \';
}
?>
</div>
<?php wp_reset_postdata(); ?>
<?php endwhile; else: ?>
<?php //error message ?>
<?php endif; ?>
<?php wp_reset_query(); ?>