Ad

Which Hook To Modify Metadata Before Save (WooCommerce Products)?

- 1 answer

I would like to potentially modify metadata (if empty) on a WooCommerce product before it is saved. This metadata is a custom meta field that is not part of WooCommerce. That means I need to check the given metadata first – as opposed to setting a value always, regardless.

Ad

Answer

Pretty ugly, but this works in my case:

function my_save_product_meta( $product ) {

    // only modify if empty; replacement / action is simple enough so that we 
    // need not to worry about sanitization.
    if (
        isset($_POST['my_custom_field']) 
    &&  empty(trim($_POST['my_custom_field']))
    ) {
        $_POST['my_custom_field'] = '0';
    }
}
add_action('woocommerce_admin_process_product_object', 'my_save_product_meta', 10, 1);

Works for saving new products as well as updating existing ones.

Ad
source: stackoverflow.com
Ad