skip to Main Content

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


  1. does this make a difference?

    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);
    
        $product->save();
        error_log ("NUMBER NOW : ".$product->get_total_sales());
    
        wp_die();
    }
    
    Login or Signup to reply.
  2. 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.

    // define the woocommerce_init callback 
    function pc_set_total_sales( ) { 
        $query = new WC_Product_Query( array(
            'limit' => -1,
            'orderby' => 'date',
            'order' => 'DESC',
            // 'return' => 'ids',
        ) );
        $products = $query->get_products();
    
        foreach($products as $product){
            $myArr = [1674, 1213, 982];
            if ( in_array($product->id, $myArr) ){
                $product->set_total_sales(1);
            } else{
                $product->set_total_sales(0);
            }
            $product->save();
        }
    };
    add_action( 'init', 'pc_set_total_sales', 10 );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search