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

WooCommerce可变产品ID1010属性检测及订单页代码问题修复

WooCommerce订单详情页多属性商品展示修复方案

直接把下面的代码放到主题的functions.php文件里就能解决问题:

add_action( 'woocommerce_view_order', 'display_book_terms_on_order_details', 20 );
function display_book_terms_on_order_details( $order_id ) {
    // 获取当前订单对象
    $order = wc_get_order( $order_id );
    if ( ! $order ) return;

    // 逐个遍历订单里的每件商品
    foreach ( $order->get_items() as $item ) {
        $product = $item->get_product();
        
        // 检查这件商品是不是ID1010的可变产品,或是它的变体
        if ( $product && ( $product->get_id() == 1010 || $product->get_parent_id() == 1010 ) ) {
            // 优先从订单项元数据拿属性值——这是用户购买时实际选的,最准确
            $book_term = $item->get_meta( 'book terms' );
            
            // 万一订单项没存属性,再从变体产品的属性里读取
            if ( empty( $book_term ) && $product->is_type( 'variation' ) ) {
                $attributes = $product->get_attributes();
                $book_term = $attributes['book terms']->get_options()[0] ?? '';
            }

            // 有值就单独输出这件商品的信息
            if ( $book_term ) {
                echo '<div style="margin: 15px 0; padding: 10px; background-color: #f8f8f8; border-radius: 4px;">';
                echo '<p><strong>书籍条款:</strong>' . esc_html( $book_term ) . '</p>';
                echo '<p><strong>购买数量:</strong>' . esc_html( $item->get_quantity() ) . '</p>';
                echo '</div>';
            }
        }
    }
}

原代码的问题根源

  • 变量覆盖:你之前应该把属性值变量放在了循环外面,每次循环都会覆盖之前的值,最后只留下最后一次(或错误的第一个)结果。
  • 未逐个处理订单项:没有遍历订单里的每一件商品,而是直接取了全局的产品属性,自然拿不到多件不同属性的信息。

修复的核心调整

  • 遍历订单的每一个订单项,确保每件商品都被单独检查和输出
  • 优先从订单项元数据获取属性值——这是用户购买时实际选择的,比从产品对象读取更可靠
  • 兼容可变产品的变体,确保属性值能正确获取
  • 每件商品的信息单独输出,不会互相覆盖

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 03:57:36