Reputation: 123
I'm trying to have the product's stock quantity set to zero when there is an specific post_meta
I'm hooking into 'woocommerce_update_product' . When I click "update", this starts, and does update correctly; however, the action never finishes. ( the page is just loading ... )
When I refresh the page and check the stock, this is modified correctly.
Am I doing anything wrong?
This is my code
add_action('woocommerce_update_product', 'sv_set_no_stock_when_discontinued', 10, 1);
function sv_set_no_stock_when_discontinued($prodId){
$discontinued = get_post_meta($prodId, '_is_discontinued', true);
if($discontinued == 'yes'){
$product = wc_get_product($prodId);
// Using WC setters
$product->set_manage_stock(true);
$product->set_stock_quantity(0);
$product->set_stock_status('outofstock');
// Save Product
$product->save();
}
}
After leaving it for a while, i get the following errors:
Fatal error: Allowed memory size of 1077936128 bytes exhausted (tried to allocate 20480 bytes) in \wp-includes\meta.php on line 1078
Fatal error: Allowed memory size of 1077936128 bytes exhausted (tried to allocate 20480 bytes) in \wp-includes\class-wp-fatal-error-handler.php on line 72
Upvotes: 0
Views: 5269
Reputation: 254492
The WC_Product Object is already included as 2nd argument for woocommerce_update_product
Hook… So you can change a little bit your code like:
But as this hook is located on WC_Product_Data_Store_CPT
Class, It doesn't really like the WC_Product
setter methods and especially save()
method.
So instead we will replace this hook with the following:
add_action( 'woocommerce_admin_process_product_object', 'set_no_stock_if_discontinued' );
function set_no_stock_if_discontinued( $product ) {
if( $product->get_meta('_is_discontinued') === 'yes'
|| ( isset($_POST['_is_discontinued'])
&& esc_attr($_POST['_is_discontinued']) === 'yes' ) ) {
// Using WC setters
$product->set_manage_stock(true);
$product->set_stock_quantity(0);
$product->set_stock_status('outofstock');
}
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
Note: The
save()
method is not needed as it's triggered just after this hook.
Global note: You can also set "manage stock" to false.
Upvotes: 5