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

如何在WooCommerce新订单Telegram通知中添加商品名称与SKU

WooCommerce新订单Telegram通知添加商品名称与SKU的修改方案

以下是修改后的完整代码,已加入商品名称、SKU及数量的明细展示,同时优化了部分原有逻辑:

add_action( 'woocommerce_new_order', 'telegram_notification', 10, 1 );
function telegram_notification( $order_id ) {
    $order = wc_get_order( $order_id );

    // 构建基础通知内容
    $text = "*" . __( '新订单通知' ) . "*\n\n";
    $text .= __( '订单编号' ) . ': ' . $order_id . "\n";
    $text .= __( '订单状态' ) . ': ' . wc_get_order_status_name( $order->get_status() ) . "\n";
    $text .= __( '订单日期' ) . ': ' . $order->get_date_created()->format('Y-m-d H:i:s') . "\n";
    $text .= __( '客户邮箱' ) . ': ' . $order->get_billing_email() . "\n";
    $text .= __( '订单总价' ) . ': ' . $order->get_total() . ' ' . $order->get_currency() . "\n";
    $text .= __( '支付方式' ) . ': ' . $order->get_payment_method_title() . "\n";

    // 添加商品明细(名称+SKU+数量)
    $text .= "\n" . "*" . __( '商品明细' ) . "*\n";
    foreach ( $order->get_items() as $item ) {
        $product = $item->get_product();
        $product_name = $item->get_name();
        // 处理无SKU的商品
        $product_sku = $product ? $product->get_sku() : __( '无SKU' );
        $quantity = $item->get_quantity();
        
        $text .= "- " . $product_name . " (SKU: " . $product_sku . ") x " . $quantity . "\n";
    }

    // 发送Telegram通知,转义特殊字符并使用WordPress原生函数
    $encoded_text = urlencode( $text );
    $bot_token = '12345:xxxxx-zzzzz'; // 替换为你的机器人Token
    $chat_id = '-1234567890'; // 替换为你的群组ID
    $url = "https://api.telegram.org/bot{$bot_token}/sendMessage?parse_mode=markdown&chat_id={$chat_id}&text={$encoded_text}";
    
    wp_remote_get( $url );
}

关键修改说明

  1. 调整钩子优先级:将原优先级1改为10,确保订单数据完全加载后再执行通知逻辑,避免数据获取异常。
  2. 优化日期展示:用get_date_created()获取订单创建日期并格式化,替代原有的修改日期,更符合订单通知的场景需求。
  3. 商品明细获取:通过$order->get_items()遍历所有订单项,逐个获取商品名称、SKU和购买数量,其中对无SKU的商品做了兼容处理。
  4. 请求优化:用WordPress原生的wp_remote_get()替代file_get_contents,兼容性更强,同时对通知文本做urlencode处理,避免特殊字符导致请求失败。
  5. 格式优化:统一使用\n换行,同时保持Telegram的Markdown格式,让通知内容更清晰易读。

内容的提问来源于stack exchange,提问作者Alexandru T.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 19:37:33