我想为每个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);
}
}
我只是不确定如何检索常规价格和销售价格?
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文件中。
代码经过测试并正常工作。
希望这有帮助!