WooCommerce产品更新–检查字段的值是否已更改

我正在使用以下代码在woocommerce中挂钩产品更新:

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

与先前存储的产品版本相比,有没有办法检查某些字段是否已更改?

谢谢!

ooygg 回答:WooCommerce产品更新–检查字段的值是否已更改

我建议使用其他动作。我用它来识别订单更改,但实际上它可以用于任何与woocomercce相关的对象类型(订单,产品,优惠券,订阅等)

woocommerce_before_[objectName]_object_save

出于您的目的,您可以使用:

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

}

话虽如此,您需要小心,因为此挂钩可能是从不同的触发器(某些后台进程等)启动的。您可能需要进行一些谨慎的测量:

  • 使用$_POST['action'] == 'editpost'确保操作是 从管理员编辑页面实际单击“更新”。
  • 使用(is_admin())仅将其限制为管理区域
  • 您可以使用(!defined('DOING_CRON'))来确保它不会在任何cron执行中运行
  • ,您可以使用(!defined('DOING_AJAX'))来确保它不会在ajax调用中运行

通过这种方式,您只能将其限制为希望捕获的确切动作。

,

我知道最好的方法是使用散列。

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,$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,$hash2);
    }
}

要从产品对象中获取数据,请检查以下资源: https://businessbloomer.com/woocommerce-easily-get-product-info-title-sku-desc-product-object/

我希望这适合您的情况

本文链接:https://www.f2er.com/3090590.html

大家都在问