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

如何在WooCommerce中获取处理状态订单数?短代码开发失败求助

制作WooCommerce处理状态订单数量短代码的问题

我需要制作一个短代码,用来显示WooCommerce中处于「处理中」状态的订单总数。找了一段能统计处理中订单数的代码,尝试改成短代码后无法正常运行。


第一次尝试的代码(无法正常运行)

function get_count_for_processing( $status ){
    global $wpdb;
    // 当订单状态缺少'wc-'前缀时为其添加
    $status = 'wc-' . str_replace('wc-', '', $status);

    return $wpdb->get_var("
        SELECT count(ID)  FROM {$wpdb->prefix}posts WHERE post_status LIKE '$status' AND `post_type` LIKE 'shop_order'
    ");
    // 显示“processing”订单数量
    echo get_count_for_processing( "processing" );
}
add_shortcode('get_count_processing', 'get_count_for_processing');

问题分析

  1. 短代码回调逻辑错误:短代码的回调函数必须返回内容,不能直接用echo输出,否则会导致内容提前输出打乱页面结构;同时函数内部递归调用自身,逻辑完全混乱。
  2. SQL注入风险:直接将变量拼入SQL语句,存在安全隐患。
  3. 参数处理不当:短代码的回调函数默认第一个参数是属性数组,不是直接传入状态值。

修正后的可用代码

function get_processing_order_count( $atts ){
    global $wpdb;
    
    // 初始化短代码属性,默认统计processing状态订单
    $atts = shortcode_atts( array(
        'status' => 'processing'
    ), $atts );

    // 统一处理订单状态前缀,确保为wc-开头
    $status = 'wc-' . str_replace('wc-', '', $atts['status']);

    // 使用wpdb的prepare方法防止SQL注入,同时准确查询订单数量
    $order_count = $wpdb->get_var( $wpdb->prepare(
        "SELECT COUNT(ID) FROM {$wpdb->prefix}posts WHERE post_status = %s AND post_type = 'shop_order'",
        $status
    ) );

    // 返回统计结果,短代码会自动渲染到页面
    return $order_count;
}
add_shortcode('processing_order_count', 'get_processing_order_count');

使用方法

  • 显示处理中订单数量:[processing_order_count]
  • 显示其他状态订单数量(比如已完成):[processing_order_count status="completed"]

第二次尝试的代码(完全无法运行)

function action_woocommerce_single_product_summary() {
    global $product;
    // 是否为WC产品
    if ( is_a( $product, 'WC_Product' ) ) {
        // 设置订单状态(不含wc-)
        $statuses = array( 'completed' );

        // 调用函数
        $total_sales = get_product_total_sales_by_order_status( $product->get_id(), $statuses );

        // 显示结果
        if ( $total_sales >= 1 ) {
            echo sprintf( __( 'Total sales: %d', 'woocommerce' ), $total_sales );
        } else {
            echo __( 'N/A', 'woocommerce' );
        }
    }
}
add_shortcode('test123123', 'action_woocommerce_single_product_summary');

问题分析

  1. 依赖上下文缺失:这个函数原本是为产品页面的钩子设计的,依赖全局$product变量,但短代码可能在没有产品上下文的场景(比如首页、文章页)调用,此时$product为空,逻辑无法执行。
  2. 调用未定义函数:代码中使用了get_product_total_sales_by_order_status,但这个函数并非WooCommerce内置函数,需要自行实现,否则会直接抛出致命错误。
  3. 短代码输出方式错误:同样直接用echo输出内容,不符合短代码的规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 20:13:33