Change product status if prices are updated in Woocommerce 3

空扰寡人 提交于 2019-12-24 10:17:46

问题


I need to change product post_status in a hook. I trying to make product get back to "pending" status everytime vendor change the price.

add_action( 'updated_post_meta', 'mp_sync_on_product_save', 10, 4 );
function mp_sync_on_product_save( $meta_id, $post_id, $meta_key, $meta_value ) {
    if ( $meta_key == '_price' ) { // edited price
        if ( get_post_type( $post_id ) == 'product' ) {
            $product = wc_get_product( $post_id );
            $product['post_status'] = 'pending'; //how to update this?
            // var_dump($product_id);var_dump($product);die('test');

        }
    }
}

Can someone tell me what function could do this: "$product['post_status'] ='pending';"?


回答1:


The following code will change the product status to pending if anyone else than the "administrator" user role update product prices in backend:

add_action( 'woocommerce_product_object_updated_props', 'change_status_on_product_object_updated_prices', 10, 2 );
function change_status_on_product_object_updated_prices( $product, $updated_props ) {

    $changed_props = $product->get_changes();

    if ( $product->get_status() !== 'pending' && ( in_array( 'regular_price', $updated_props, true ) ||
    in_array( 'sale_price', $updated_props, true ) ) && ! current_user_can( 'administrator' ) )
    {
        wp_update_post( array( 'ID' => $product->get_id(), 'post_status' => 'pending' ) );
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

The "administrator" user role will not be affected by the code… You should also check that "Vendors user role is not able to change the product post status.



来源:https://stackoverflow.com/questions/52977326/change-product-status-if-prices-are-updated-in-woocommerce-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!