【发布时间】:2022-01-22 00:11:14
【问题描述】:
我试图弄清楚如何在单个产品页面中将所有变体价格显示为文本。
例如,如果产品有 5 个不同的价格,1 - 500、2 - 900、3 - 2100、4 - 2500、5 - 3000 我希望它在所有产品页面上以文本形式显示。
这样:
变化
1 - 500
2 - 900。
现在我手动执行此操作,将它们全部写下来,这样用户就不必在下拉菜单中向下滚动以查看价格,但我希望在更改价格时自动完成,因此我不必更改此文本每次。我尝试了不同的钩子,但找不到合适的。
我试过这个,但无法使用钩子并在产品页面中显示它
add_filter( 'woocommerce_get_price_html', 'custom_price_format', 10, 2 );
add_filter( 'woocommerce_variable_price_html', 'custom_price_format', 10, 2 );
function custom_price_format( $price, $product ) {
// 1. Variable products
if( $product->is_type('variable') ){
// Searching for the default variation
$default_attributes = $product->get_default_attributes();
// Loop through available variations
foreach($product->get_available_variations() as $variation){
$found = true; // Initializing
// Loop through variation attributes
foreach( $variation['attributes'] as $key => $value ){
$taxonomy = str_replace( 'attribute_', '', $key );
// Searching for a matching variation as default
if( isset($default_attributes[$taxonomy]) && $default_attributes[$taxonomy] != $value ){
$found = false;
break;
}
}
// When it's found we set it and we stop the main loop
if( $found ) {
$default_variaton = $variation;
break;
} // If not we continue
else {
continue;
}
}
// Get the default variation prices or if not set the variable product min prices
$regular_price = isset($default_variaton) ? $default_variaton['display_price']: $product->get_variation_regular_price( 'min', true );
$sale_price = isset($default_variaton) ? $default_variaton['display_regular_price']: $product->get_variation_sale_price( 'min', true );
}
// 2. Other products types
else {
$regular_price = $product->get_regular_price();
$sale_price = $product->get_sale_price();
}
// Formatting the price
if ( $regular_price !== $sale_price && $product->is_on_sale()) {
// Percentage calculation and text
$percentage = round( ( $regular_price - $sale_price ) / $regular_price * 100 ).'%';
$percentage_txt = __(' Save', 'woocommerce' ).' '.$percentage;
$price = '<del>' . wc_price($regular_price) . '</del> <ins>' . wc_price($sale_price) . $percentage_txt . '</ins>';
}
return $price;
}
【问题讨论】:
标签: woocommerce product price product-variations