Woocommerce 函数 set_total_sales() 没有设置和保存 total_sales 到数据库

Woocommerce function set_total_sales() is not setting and saving total_sales to database

我正在 woocommerce 中开发一个儿童主题。 在一个函数中,我尝试使用默认的 get_total_sales()set_total_sales() 来添加总销售额并在从 AJAX(单击按钮下载时)调用时保存。

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();
}

服务器日志如下所示:

[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

看起来不错,但不... 下载计数未保存到数据库中。 当我刷新页面时,

get_total_sales() 将 return 变回 0。

这里可能有什么问题?

这有什么不同吗?

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();
}

如果想为特定产品设置总销售额,也许对某些人会有所帮助。

注意:每次重新加载页面时都会设置总销售额。具体场景需要的话请相应添加条件等。

// 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 );