我想为每个WooCommerce产品添加自定义meta_key
值这将是折扣率:
_discount_rate = ((_sale_price-_regular_price_)/(_regular_price)*100)
我正在试图弄清楚如何为WooCommerce函数woocommerce_process_product_meta
添加过滤器:
add_filter('woocommerce_process_product_meta', 'mytheme_product_save_discountrate');
function mytheme_product_save_discountrate($post_id) {
if (get_post_meta($post_id, "_sale_price")) {
$regular_price = get_post_meta($post_id, "_regular_price");
$sale_price = get_post_meta($post_id, "_sale_price");
$discount_rate = ($sale_price - $regular_price) / $regular_price * 100);
update_post_meta($post_id, '_discount_rate', $discount_rate);
}
}
我只是不确定如何检索常规和促销价格?
答案 0 :(得分:1)
WooCommerce有一个内置的方法来获得价格
get_regular_price()
和get_sale_price()
。
以下是代码:
add_action('woocommerce_process_product_meta', 'mytheme_product_save_discountrate', 999); //<-- check the priority
function mytheme_product_save_discountrate($post_id) {
$_product = wc_get_product($post_id);
$regular_price = $_product->get_regular_price();
$sale_price = $_product->get_sale_price();
// $_product->get_price();
if (!empty($sale_price)) {
$discount_rate = (($sale_price - $regular_price) / ($regular_price)) * 100; //replace it with your own logic
update_post_meta($post_id, '_discount_rate', $discount_rate);
}
}
代码进入您的活动子主题(或主题)的functions.php
文件。或者也可以在任何插件PHP文件中。
代码已经过测试并且有效。
希望这有帮助!