I need to reset all stock in woocommerce to outofstock. Or set the stock on all products to zero. One or the other. Doesn't matter.
I have written this so far.
function clear_current_stock(){
$sql = "UPDATE wp_postmeta SET meta_value = 'outofstock' WHERE meta_value = 'instock' AND meta_key = '_stock_status'";
// run queries
if ($wpdb->query( $sql ) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record";
}
}
And I have called the function like this. (Just to test it and make sure it's working)
<?php clear_current_stock(); ?>
But the function isn't doing anything. Please help.
there is a similar question here .
But It hasn't helped me.
What I need for the finished piece of code. Is to click a button which calls this function. then sets all the posts of type product to zero stock. or outofstock
My process to the answer.
Firstly I went into MYSQL workbench and ran the query in workbench. This showed me that there was an error selecting the Database.
I fixed my sql query so it was working in MYSQL workbench. Then I continued with my function.
I found that in my function I wasn't declaring my variable.
I had to declare my variable first for $wpdb to work in the first place. Which as shown above was not been done.
This is the final function working 100%
// Clear Stock
function clear_current_stock(){
// Declare the $wpdb var
global $wpdb;
// Run My SQL Query (My Query is setting the meta value for stock to zero)
$wpdb->query("UPDATE wp_postmeta SET meta_value = 0 WHERE meta_key = '_stock'");
// Check if there were any errors or if my query was successful.
if ( is_wp_error( $wpdb ) ) {
echo $wpdb->get_error_message();
}
else {
echo 'true';
}
}
Then you just need to call the function where ever or when ever you want to run the query. This can be done like so.
<?php clear_current_stock(); ?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.