OhMad
OhMad

Reputation: 7289

WooCommerce product update – check if a field's value has changed

I'm using the following code to hook a product update in woocommerce:

add_action('woocommerce_update_product', 'on_update_product', 10, 2);
function on_update_product($product_id, $product){
    // code here
}

Is there a way to check if certain fields have changed, compared to the previously stored version of the product?

Thanks!

Upvotes: 2

Views: 2161

Answers (2)

Shir Gans
Shir Gans

Reputation: 2027

I would recommend hooking to another action. I use it to identify changes in orders, but it actually can use for any woocomercce related object types (orders, products, coupons, subscriptions etc.)

woocommerce_before_[objectName]_object_save

for your purpose you can use:

add_action('woocommerce_before_product_object_save', 'identify_product_change', 100, 2);
function identify_product_change($product, $data){

    $posted_info = $_POST; // Use this to get the new information 
    $price = $product->get_price(); //Example of getting the "old" product information

}

Having that said, you need to be careful, since this hook may be initiated from different triggers (some background processes etc). You may want to have some caution measurements:

  • use $_POST['action'] == 'editpost' to make sure the action is an actual "Update" click from the admin edit page.
  • use (is_admin()) to limit it only to admin area
  • you can use (!defined('DOING_CRON')) to make sure it won't run on any cron execution
  • and you can use (!defined('DOING_AJAX')) to make sure it won't run on ajax calls

this way you can limit it only to the exact action you wish to catch.

Upvotes: 0

Matthijs Knigge
Matthijs Knigge

Reputation: 402

The best way to do this that I know is with hashes.

add_action('woocommerce_update_product', 'on_update_product', 10, 2);
function on_update_product($product_id, $product){
    //create a hash from data you want to track
    $hash = md5(json_encode([
        $product->get_name(),
        $product->get_price(),
        "etc....."
    ]));
    //get the hash before the product update
    $hashBefore = get_post_meta( $product_id, "hashKey", true );
    //check if de hash is diffrend
    if ($hash !== $hashBefore) {
        // Store the new hash
        add_post_meta($product_id, "hashKey", $hash);
        // exicute your code
        // .....
    }

    // you can duplicate this process if you want to track individual fields
    $hash2 = md5(json_encode([
        $product->get_sku(),
    ]));
    $hashBefore2 = get_post_meta( $product_id, "hashKey2", true );
    if ($hash2 !== $hashBefore2) {
        add_post_meta($product_id, "hashKey2", $hash2);
    }
}

To get data out of the product object check this resource: https://businessbloomer.com/woocommerce-easily-get-product-info-title-sku-desc-product-object/

I hope this suits your situation

Upvotes: 2

Related Questions