如何获得WooCommerce用户总支出金额

问题描述

使用以下简码,我试图获取用户的总支出金额,但是这会减慢页面加载速度(6秒)。

是否可以优化此代码以缩短加载时间?

while(1) { // break on good input
      printf("Please enter your choice of 1,2 or 3:\n");
      try = scanf("%d",&selection);
      if(try!=1 || selection < 1 || selection > 3){
          if(try == EOF)
          {
              return 0;
          }
           printf("\nThe input was not 1,2 or 3. Please try again.\n");
           int discard;
           {
               do{
                   discard = getchar();
                   if(discard == EOF) { return 0;} // catches EOF after bad char
               }while(!isspace(discard));
           }
      }
      else break;
}

解决方法

您可以通过以下方式简单地使用WC_Customer method get_total_spent()

add_shortcode('user_total_spent','get_user_total_spent');

function get_user_total_spent( $atts ) {
    extract( shortcode_atts( array(
        'user_id' => get_current_user_id(),),$atts,'user_total_spent' ) );

    if( $user_id > 0 ) {
        $customer = new WC_Customer( $user_id ); // Get WC_Customer Object

        $total_spent = $customer->get_total_spent(); // Get total spent amount

        return wc_price( $total_spent ); // return formatted total spent amount
    }
}

// USAGE: [user_total_spent] or [user_total_spent user_id="118"]

代码进入您的活动子主题(活动主题)的function.php文件中。经过测试,可以正常工作。