I have constructed the below function to work in conjunction with a button displayed on the edit product page. It is designed to generate some description text based on the title and SKU of the product. The code works perfectly for ‘simple’ products, but I am struggling to get it to work for ‘variable’ products too.
What exactly do I need to do to get it to work correctly for both simple and variable products?
The current behaviour is:
- When triggered on a simple product, it adds the new description or updates the old one to the new one.
- When triggered on a variable product, it updates the main description, but deletes all variations which were previously set up on the product.
add_action('woocommerce_process_product_meta', 'update_and_save_utapd');
function update_and_save_utapd() {
if(isset($_POST['button_new_update_description'])){
$product_id = wc_get_product(get_the_ID());
$wcProduct = new WC_Product($product_id);
$get_title = $wcProduct->get_name();
$get_mpn = $wcProduct->get_meta('sp_wc_barcode_field');
$get_description = $wcProduct->get_description();
$output = '';
if(!empty($get_title)){
$output .= "<p>The " . $get_title;
}if(!empty($get_mpn)){
$output .= " (MPN: " . $get_mpn . ").";
}if(!empty($get_description)){
$wcProduct->set_description($output);
$wcProduct->save();
return "<div>SUCCESS: YOU HAVE UPDATED YOUR DESCRIPTION.</div>";
}elseif(empty($get_description)){
$wcProduct->set_description($output);
$wcProduct->save();
return "<div>SUCCESS: YOU HAVE GENERATED A NEW DESCRIPTION.</div>";
}
}
}
2
Answers
With the
woocommerce_process_product_meta
hook you already have the product id and the product object available. Here you will find more information.To verify that the button has been clicked you must also check its value, in addition to the
isset()
function.First when using action hooks in backend that save product data, you can’t return a string (a text) as you are trying to do and anyway, it will never be displayed
Now since WooCommerce 3 you can use
woocommerce_admin_process_product_object
much better hook that include theWC_Product
Object as function argument and there is no need to usesave()
method at the end of your code as once this hook is triggered the save() method is auto applied.So we can simplify your code:
Code goes in functions.php file of the active child theme (or active theme). It should better work now, without throwing errors.