在woocommerce_order_item_meta_end钩子中使用get_cart()方法时出错

时间:2017-03-01 11:20:37

标签: php wordpress woocommerce orders email-notifications

我有这个代码,它的功能是在woocommerce订单详细信息电子邮件模板中添加一列,但是当我发送发票时,我收到此错误消息说:

  

致命错误:未捕获错误:在第1245行的http:\ mysite.com \ functions.php中调用null上的成员函数get()

使用此代码时:

add_action( 'woocommerce_order_item_meta_end', 'order_custom_field_in_item_meta_end', 10, 4 );
function order_custom_field_in_item_meta_end( $item_id, $item, $order, $cart_item) {
    global $woocommerce;

    do_action( 'woocommerce_review_order_before_cart_contents' );

    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );

        if ( $_product && $_product->exists() && $cart_item['quantity'] > 0 && apply_filters( 'woocommerce_checkout_cart_item_visible', true, $cart_item, $cart_item_key ) ) {
            echo '<td class="td">'.$_product->get_price_html().'</td>';
        }
    }

    do_action( 'woocommerce_review_order_after_cart_contents' );

}

This is the result of the email template, I used a plugin called woocommerce email test

我的问题是,当我从订单发送发票或任何其他电子邮件通知时,会收到错误。

我做错了什么以及如何解决这个问题?

由于

2 个答案:

答案 0 :(得分:1)

很抱歉,您无法将 WC()->cart 对象用于订单或电子邮件,因为购物车已在结帐时处理并已清空。相反,你可以使用函数在 woocommerce_order_item_meta_end 中挂钩的变量参数,这些参数是 $item_id $item $order $plain_text ......

  

您不需要任何foreach循环来获取订单商品数据,因为您可以使用直接$item参数获取产品的ID。

以下是适用于简单或可变产品的正确代码(但最后请参阅)

add_action( 'woocommerce_order_item_meta_end', 'order_custom_field_in_item_meta_end', 10, 4 );
function order_custom_field_in_item_meta_end( $item_id, $item, $order, $plain_text ) {

    do_action( 'woocommerce_review_order_before_cart_contents' );

    if( $item['variation_id'] > 0 ){
        $product = wc_get_product($item['variation_id']); // variable product
    } else {
        $product = wc_get_product($item['product_id']); // simple product 
    }

    // Be sure to have the corresponding "Cost each" column before using <td> tag
    echo '<td class="td">'.$product->get_price_html().'</td>';

    do_action( 'woocommerce_review_order_after_cart_contents' );

}
  

如果在之前尚未创建(或定义)“每个费用”列,则无法使用html <td> 标记

代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中。

代码经过测试并有效。

答案 1 :(得分:0)

问题是,只有在下订单后才会触发 woocommerce_order_item_meta_end 操作。因此,您的代码段中不存在 WC() - &gt;购物车的范围。

您可以使用 $ order-&gt; get_items()来获取订单商品。

请以这种方式修改您的代码以使其正常工作

add_action( 'woocommerce_order_item_meta_end', 'order_custom_field_in_item_meta_end', 10, 4 );
function order_custom_field_in_item_meta_end( $item_id, $item, $order) {
    do_action( 'woocommerce_review_order_before_cart_contents' );

    foreach ( $order->get_items() as $cart_item_key => $cart_item ) {
        // Do something here
    }

    do_action( 'woocommerce_review_order_after_cart_contents' );

}