Adr*_*ian 2 php wordpress product woocommerce price
使用 Woocommerce,我使用以下代码成功地从产品档案页面中删除了销售徽章和价格:
\n\n// Remove Sales Flash\nadd_filter('woocommerce_sale_flash', 'woo_custom_hide_sales_flash');\nfunction woo_custom_hide_sales_flash()\n{\n return false;\n}\n\n// Remove prices on archives pages\nremove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 );\nRun Code Online (Sandbox Code Playgroud)\n\n所有产品都是可变产品,所有变体的价格相同。实际上所有价格都是促销价。
\n\n我想在单个产品页面中的每个可变价格范围后添加折扣百分比。我尝试使用以下代码:
\n\nadd_filter( 'woocommerce_sale_price_html', 'woocommerce_custom_sales_price', 10, 2 );\nfunction woocommerce_custom_sales_price( $price, $product ) {\n $percentage = round( ( ( $product->regular_price \xe2\x80\x93 $product->sale_price ) / \n $product->regular_price ) * 100 );\n return $price . sprintf( __(' Save %s', 'woocommerce' ), $percentage . '%' );\n}\nRun Code Online (Sandbox Code Playgroud)\n\n但我什么也没得到
\n\n我做错了什么,该怎么办?
\n\n对此的任何帮助将不胜感激。
\n我一直在测试代码,当您的目标是可变产品的销售价格范围时,最好在woocommerce_format_sale_price位于wc_format_sale_price()函数中的过滤器挂钩中使用自定义挂钩函数。
当所有变体具有相同的价格时,这将允许在价格范围后显示保存的折扣百分比。如果变体价格不同,则该百分比将仅出现在变体价格上。
所以我重新审视了你的代码:
// Removing sale badge
add_filter('woocommerce_sale_flash', '__return_false');
// Removing archives prices
remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 );
// Add the saved discounted percentage to variable products
add_filter('woocommerce_format_sale_price', 'add_sale_price_percentage', 20, 3 );
function add_sale_price_percentage( $price, $regular_price, $sale_price ){
// Strip html tags and currency (we keep only the float number)
$regular_price = strip_tags( $regular_price );
$regular_price = (float) preg_replace('/[^0-9.]+/', '', $regular_price);
$sale_price = strip_tags( $sale_price );
$sale_price = (float) preg_replace('/[^0-9.]+/', '', $sale_price);
// Percentage text and calculation
$percentage = __('Save', 'woocommerce') . ' ';
$percentage .= round( ( $regular_price - $sale_price ) / $regular_price * 100 );
// return on sale price range with "Save " and the discounted percentage
return $price . ' <span class="save-percent">' . $percentage . '%</span>';
}
Run Code Online (Sandbox Code Playgroud)
代码位于活动子主题(活动主题)的 function.php 文件中。
经过测试并有效。
| 归档时间: |
|
| 查看次数: |
2934 次 |
| 最近记录: |