• Resolved suiluj

    (@suiluj)


    Hello i am updating the product meta data on the hook woocommerce_update_product.

    The reason is i want to calculate some custom fields.

    But i have the problem that the update of the meta data triggers the hook itself again. So it does never stop.

    
    function change_unit_price($product_id)
    {
        //test get data
        $_product = wc_get_product($product_id);
        $_regular_price = $_product->get_regular_price();
        $_sale_price = $_product->get_sale_price();
        $_meta_data = $_product->get_meta_data();
        
        // test set value
        $_product->update_meta_data('_unit_price_regular', "898");
        $_product->save();
    
    }
    add_action('woocommerce_update_product', 'change_unit_price', 99, 1);
    

    Does someone has a solution for this or is there a workflow i don’t know yet? This is my first try with wordpress plugins.

    • This topic was modified 5 years, 10 months ago by suiluj.
Viewing 1 replies (of 1 total)
  • Thread Starter suiluj

    (@suiluj)

    i found the solution:
    Stack Exchange WordPress

    before saving you can remove the hook itself.

    
    function calc_unit_prices($product_id)
    {
        $_product = wc_get_product($product_id);
    
        $_product->update_meta_data('_unit_price_regular', 29.2);
    
        //If calling wp_update_post, unhook this function so it doesn't loop infinitely
        remove_action('woocommerce_update_product', 'calc_unit_prices', 99, 1);
    
        // call wp_update_post update, which calls save_post again. E.g:
        $_product->save();
    
        // re-hook this function
        add_action('woocommerce_update_product', 'calc_unit_prices', 99, 1);
    
    }
    
    add_action('woocommerce_update_product', 'calc_unit_prices', 99, 1);
    
Viewing 1 replies (of 1 total)

The topic ‘Update Product Metadata Save Product Recursive problem’ is closed to new replies.