dongwan5381 2017-03-01 11:20 采纳率: 100%
浏览 130

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

I have this code, its function is to add a column in woocommerce order details email template, but when I send an invoice I get this error message saying:

Fatal error: Uncaught Error: Call to a member function get() on null in http:\mysite.com\functions.php on line 1245

when using this code:

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

My problem here, is that when I send an invoice or any other email notification from the order it gets an error.

What I am doing wrong and how to solve this?

Thanks

  • 写回答

2条回答 默认 最新

  • douliu8327 2017-03-01 15:07
    关注

    The problem is that the action woocommerce_order_item_meta_end is get triggered only after placing the order. so that the scope of the WC()->cart is not exists inside your code snippet.

    You can use $order->get_items() to get order items.

    Please modify your code this way to make it work

    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' );
    
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 用三极管设计—个共射极放大电路
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示