我有这段代码,它的功能是在woocommerce order details电子邮件模板中添加一个列,但是当我发送发票时,我会收到这样的错误消息:
致命错误: Uncaught错误:在第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' );
}

我在这里的问题是,当我从订单发送发票或任何其他电子邮件通知时,它会出错。
我做错了什么以及如何解决这个问题?
谢谢
发布于 2017-03-01 16:03:26
对不起,您不能使用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' );
}如果您的“每个成本”列还没有在
<td>之前创建(或定义),您就不能使用html标记。
代码在您的活动子主题(或主题)的function.php文件中,或者在任何插件文件中。
对代码进行了测试和工作。
发布于 2017-03-01 15:07:56
问题是,只有在下订单后才触发动作woocommerce_order_item_meta_end。这样,WC()->cart的作用域就不存在于代码片段中。
您可以使用$order->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' );
}https://stackoverflow.com/questions/42530344
复制相似问题