WooCommerce 服装 meta_key

WooCommerce costum meta_key

我想为每个 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 has an inbuilt methods to get the price get_regular_price() and 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 文件中。
代码已经过测试并且可以工作。

希望对您有所帮助!