You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce短代码按产品ID统计总营收功能失效

WooCommerce指定产品ID总营收短代码修复

原代码失效核心原因

  • 未关联WooCommerce存储订单-商品对应关系的两张核心表,无法匹配订单和指定商品
  • SQL中写的['id']是无效语法,既没有读取短代码传入的id参数,也没有添加对应的商品ID过滤规则
  • SELECT字段存在语法错误,多余的无效片段会导致SQL执行异常
  • 原有逻辑没有任何商品维度的过滤条件,默认统计全店符合状态的订单总金额,所以返回全店营收

修复后可直接使用的代码

function get_total_sales( $atts ) {
    $atts = shortcode_atts( array(
        'id' => '',
    ), $atts );

    $product_id = intval( $atts['id'] );
    if ( $product_id <= 0 ) {
        return '请传入有效产品ID';
    }

    global $wpdb;
    $order_statuses = apply_filters( 'woocommerce_reports_order_statuses', array( 'completed', 'on-hold', 'processing' ) );
    $status_placeholders = implode( ',', array_fill( 0, count( $order_statuses ), '%s' ) );
    $status_values = array_map( function( $status ) {
        return 'wc-' . $status;
    }, $order_statuses );

    $sales_sql = $wpdb->prepare( "
        SELECT SUM(meta.meta_value) AS total_sales, COUNT(DISTINCT posts.ID) AS total_orders
        FROM {$wpdb->posts} AS posts
        LEFT JOIN {$wpdb->postmeta} AS meta ON posts.ID = meta.post_id
        INNER JOIN {$wpdb->prefix}woocommerce_order_items AS items ON posts.ID = items.order_id
        INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS item_meta ON items.order_item_id = item_meta.order_item_id
        WHERE   meta.meta_key       = '_order_total'
        AND     posts.post_type     = 'shop_order'
        AND     posts.post_status   IN ( {$status_placeholders} )
        AND     item_meta.meta_key  = '_product_id'
        AND     item_meta.meta_value = %d
    ", array_merge( $status_values, array( $product_id ) ) );

    $order_totals = apply_filters( 'woocommerce_reports_sales_overview_order_totals', $wpdb->get_row( $sales_sql ) );

    return $order_totals->total_sales ? wc_price( $order_totals->total_sales ) : wc_price(0);
}
add_shortcode('sales', 'get_total_sales');

使用说明

  • 将上述代码添加到主题的functions.php文件或者自定义代码插件中即可生效
  • 调用短代码时传入目标产品ID,示例:[sales id="26"],其中26替换为需要统计的实际产品ID
  • 统计规则默认包含「已完成」「处理中」「保留中」三种订单状态,和原代码的统计口径保持一致
  • 返回结果自动适配站点设置的货币格式、货币符号,无需额外调整格式

注意:如果需要统计包含可变产品的子商品销量,可以额外扩展商品ID匹配逻辑,传入可变产品主ID和所有子SKU对应的ID即可。

内容的提问来源于stack exchange,提问作者Apple_ManPS3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 12:45:33