我想使用自定义字段为可变产品的供应商添加价格。因此,我使用以下代码来获取可变产品的自定义字段的最高和最低价格,但它什么也不返回。请帮助我找到如何从可变产品的自定义字段中获取价格。
// Min and max variable prices
add_filter( 'woocommerce_variable_sale_price_html', 'new_variable_price_format', 10, 2 );
add_filter( 'woocommerce_variable_price_html', 'new_variable_price_format', 10, 2 );
function new_variable_price_format( $price, $product ) {
$price = get_post_meta( $product->get_id(), 'vendor_price_regu');
echo "<pre>";
print_r($price);
echo "</pre>";
return $price;
}
由于这是关于显示的可变价格范围,因此您需要获取所有变体价格并显示最小和最大自定义格式价格以使其正常工作:
add_filter( 'woocommerce_variable_price_html', 'custom_variable_price_html', 10, 2 );
function custom_variable_price_html( $price, $product) {
$prices = [];
foreach($product->get_children() as $variation_id ){
if( $vprice = get_post_meta( $variation_id, 'vendor_price_regu', true ) )
$prices[] = $vprice;
}
if( sizeof($prices) > 0 ){
sort($prices);
$min_price = reset( $prices );
$max_price = end( $prices );
if ( $min_price == $max_price ) {
$price = wc_price($min_price);
} else {
$price = wc_price($min_price) . ' - ' . wc_price($max_price);
}
}
return $price;
}
代码位于活动子主题(或活动主题)的 function.php 文件中。应该可以。