我在主题函数中添加了此代码,以添加数量//添加数量
add_filter( 'woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_woocommerce_loop_add_to_cart_link', 10, 2 );
function quantity_inputs_for_woocommerce_loop_add_to_cart_link( $html, $product ) {
if (!is_page('wishlist')) {
if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
$html = '<form action="' . esc_url( $product->add_to_cart_url() ) . '" class="cart" method="post" enctype="multipart/form-data">';
// Access the cart items
$in_cart = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product_id = $cart_item['product_id'];
$quantity = $cart_item['quantity'];
if($product_id == $product->get_ID()){
$in_cart = true;
break;
}
}
// If we have match update quantity
if($in_cart) {
$html .= woocommerce_quantity_input( array('input_value' => $quantity), $product, false );
} else {
$html .= woocommerce_quantity_input( array(), $product, false );
}
$html .= '<button type="submit" class="button alt">' . esc_html( $product->add_to_cart_text() ) . '</button>';
$html .= '</form>';
}
return $html;
}
return $html;
}
但我在主题日志文件中得到了这个错误
function get_cart() on null
"我做错了什么"
1条答案
按热度按时间fwzugrvs1#
也许WC()函数甚至在woocommerce初始化之前就被调用了。你可以试着把代码 Package 在一个函数中,这个函数只在woocommerce初始化之后才执行。