phpwordpresswoocommercehook-woocommercemeta-key

WooCommerce costum meta_key


I would like to add a custom meta_key value to each WooCommerce product It will be the Discount rate :

_discount_rate = ((_sale_price-_regular_price_)/(_regular_price)*100)

I'm trying to figure out how to add a filter to WooCommerce function woocommerce_process_product_meta Something like:

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);
    }
}

I'm just not sure how I can retrieve the regular and sale prices?


Solution

  • WooCommerce has an inbuilt methods to get the price get_regular_price() and get_sale_price().

    Here is the code:

    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);
        }
    }
    

    Code goes in functions.php file of your active child theme (or theme). Or also in any plugin PHP files.
    Code is tested and works.

    Hope this helps!