在2.4x之前,我使用此代码段在目录和产品页面上获取价格而非最低 - 最高价格。
add_filter( 'woocommerce_variable_sale_price_html', 'wc_wc20_variation_price_format', 10, 2 );
add_filter( 'woocommerce_variable_price_html', 'wc_wc20_variation_price_format', 10, 2 );
function wc_wc20_variation_price_format( $price, $product ) {
// Main Price
$prices = array( $product->get_variation_price( 'min', true ), $product->get_variation_price( 'max', true ) );
$price = $prices[0] !== $prices[1] ? sprintf( __( 'From: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );
// Sale Price
$prices = array( $product->get_variation_regular_price( 'min', true ), $product->get_variation_regular_price( 'max', true ) );
sort( $prices );
$saleprice = $prices[0] !== $prices[1] ? sprintf( __( 'From: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );
if ( $price !== $saleprice ) {
$price = '<del>' . $saleprice . '</del> <ins>' . $price . '</ins>';
}
return $price;
}
但是因为他们更新了整个变异逻辑,所以它似乎不再那么好用了。我参考这篇官方帖子:https://woocommerce.wordpress.com/2015/09/14/caching-and-dynamic-pricing-upcoming-changes-to-the-get_variation_prices-method/
任何提示如何解决这个问题?
参考: https://github.com/woothemes/woocommerce/blob/2.4.7/includes/class-wc-product-variable.php#L257
答案 0 :(得分:0)
看看WooCommerce是如何generating the variable price html的。这应该会有很大帮助。基于此,这就是我想出的:
add_filter( 'woocommerce_variable_price_html', 'so_32738056_filter_variable_price_html', 10, 2 );
add_filter( 'woocommerce_variable_sale_price_html', 'so_32738056_filter_variable_price_html', 10, 2 );
function so_32738056_filter_variable_price_html( $price, $product ){
$prices = $product->get_variation_prices( true );
$min_price = current( $prices['price'] );
$max_price = end( $prices['price'] );
$price = $min_price !== $max_price ? sprintf( _x( 'From %1$s', 'minimum price', 'woocommerce' ), wc_price( $min_price ) ) : wc_price( $min_price );
if ( $product->is_on_sale() ) {
$min_regular_price = current( $prices['regular_price'] );
$max_regular_price = end( $prices['regular_price'] );
$regular_price = $min_regular_price !== $max_regular_price ? sprintf( _x( 'From: %1$s', 'minimum price', 'woocommerce' ), wc_price( $min_regular_price ), wc_price( $max_regular_price ) ) : wc_price( $min_regular_price );
$price = '<del>' . $regular_price . '</del> <ins>' . $price . '</ins>';
} else {
$price = $price . $product->get_price_suffix();
}
return $price;
}