我的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;
}
我想做的是,如果产品在购物车中,"添加到购物车"按钮文本应该改为"已经在购物车"。
问题似乎是$cart为空,也许可以尝试:
if ( !is_null($cart) && !$cart->is_empty() ) {. //line 7
或者检查为什么WC((->运货马车正在返回NULL
你做得对,它应该有效,我唯一能想到的是,你在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 );
});