我显示了所有产品属性的列表。在我的例子中,颜色。例如,产品的颜色可以是蓝色、和淡蓝。这些是为了在归档页面上进行过滤。
但在产品页面上,我只想展示其中一个(浅蓝色)。如果她的属性我们存在的话,有没有办法排除一个属性。
这可能是一种手动的方式,因为只有5-10个。
目前,我正在使用以下代码来显示属性:
global $product;
$pa_colors = wc_get_product_terms( $product->get_id(), 'pa_color', array( 'fields' => 'all', 'orderby' => 'menu_order' ) );
if( $pa_colors ) :
foreach ( $pa_colors as $pa_color ) :
echo $pa_color->name;
endforeach;
endif; 发布于 2020-10-02 11:30:40
有几种方法可以做到这一点
已使用的php函数
当$pa_color->name在array中找到时,我们将其替换为数组中的第一个项。如果不满足其他条件,则满足其他条件。由于重复值可能以这种方式出现,因此对数组进行筛选以获得重复的值。
global $product;
if ( is_a( $product, 'WC_Product' ) ) {
$pa_colors = wc_get_product_terms( $product->get_id(), 'pa_color', array( 'fields' => 'all', 'orderby' => 'menu_order' ) );
if( $pa_colors ) {
// Set colors, if a color is found in the array, the first item in the array will be displayed
$colors = array( 'light blue', 'blue', 'dark blue', 'moonstone blue' );
// Loop
foreach ( $pa_colors as $pa_color ) {
// in_array — Checks if a value exists in an array
if ( in_array ( $pa_color->name, $colors ) ) {
$output[] = $colors[0];
} else {
$output[] = $pa_color->name;
}
}
// Removes duplicate values from an array
$result = array_unique( $output );
// Result
echo '<pre>', print_r( $result, 1 ), '</pre>';
}
}https://stackoverflow.com/questions/63869820
复制相似问题