我在我的php代码中得到一个致命的错误,并想知道如何修复它。
致命错误: PHP致命错误:Uncaught Error: Call to a member function is_empty() on null in /home4/metis/public_html/staging/4326/wp-content/plugins/code-snippets/php/snippet-ops.php(446) : eval()'d code:7
代码:
add_filter( 'woocommerce_product_add_to_cart_text', 'woocommerce_custom_add_to_cart_text', 10, 2 );
function woocommerce_custom_add_to_cart_text( $add_to_cart_text, $product ) {
// Get cart
$cart = WC()->cart;
// If cart is NOT empty
if ( ! $cart->is_empty() ) {. //line 7
// Iterating though each cart items
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
// Get product id in cart
$_product_id = $cart_item['product_id'];
// Compare
if ( $product->get_id() == $_product_id ) {
// Change text
$add_to_cart_text = 'Already in cart';
break;
}
}
}
return $add_to_cart_text;
}我正在尝试做的是,如果产品在购物车中,“添加到购物车”按钮文本应更改为“已在购物车”。
发布于 2020-10-25 09:25:41
问题似乎是$cart是空的,也许可以试试:
if ( !is_null($cart) && !$cart->is_empty() ) {. //line 7或者检查WC()->cart;返回NULL的原因
发布于 2020-10-25 20:14:04
你做的很对,它应该可以工作,我能想到的唯一一件事就是你在没有定义WC()->cart的地方挂接得太早了,也许你可以把代码包装在以后的挂接中:
add_action('wp', function() {
add_filter( 'woocommerce_product_add_to_cart_text', function($add_to_cart_text, $product) {
if (WC()->cart->is_empty()) {
// Do your thing
}
}, 10, 2 );
});https://stackoverflow.com/questions/64519348
复制相似问题