I am working on a child theme in woocommerce.
In a function I am trying to use the default get_total_sales()
and set_total_sales()
to add total sales and save when it is called from AJAX(when a button is clicked to download).
function download_count_callback(){
//get product id from AJAX POST
$productid = $_POST['productid'];
//get product by id
$product = wc_get_product( $productid );
//get the total sales number
$downloadcount = $product->get_total_sales();
error_log ("NUMBER was : ".$downloadcount );
//add 1 to total sales
$downloadcount += 1;
error_log ("NUMBER should become : ".$downloadcount );
//get the renewed total sales number
$product->set_total_sales($downloadcount);
error_log ("NUMBER NOW : ".$product->get_total_sales());
wp_die();
}
Here’s how the server log looks like:
[23-Feb-2020 12:44:44 UTC] NUMBER was : 0
[23-Feb-2020 12:44:44 UTC] NUMBER should become : 1
[23-Feb-2020 12:44:44 UTC] NUMBER NOW : 1
It looks fine, but no…
The downloadcount was not saved into the database.
When i refresh the page,
get_total_sales()
will return back to 0.
What could be wrong here?
2
Answers
does this make a difference?
Maybe it would be helpful for someone if wants to set total sales for specific products.
Note: It will set total sales every time a page reloads. Please add some conditions etc. accordingly if you want it on specific scenarios.