WooCommerce产品列表页如何展示已加入购物车的商品数量
WooCommerce产品列表页展示已加购数量教程
你需要实现的效果为:产品列表页对应商品位置展示该商品已被当前用户加入购物车的数量,例如商品x加购3件、商品y加购5件时,列表页对应位置分别显示3和5。
你可以通过WooCommerce提供的woocommerce_loop_add_to_cart_link过滤器实现该功能,同时还可以保留列表页加购按钮的数量选择能力,完整代码如下:
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 ) { // 获取当前商品在购物车中的已加购数量 $cart_quantity = 0; if ( WC()->cart ) { foreach( WC()->cart->get_cart() as $cart_item ) { if( $cart_item['product_id'] == $product->get_id() ) { $cart_quantity = $cart_item['quantity']; break; } } } // 仅对简单产品生效,可根据需求调整产品类型判断 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">'; // 如果已加购,先展示已加购数量 if ( $cart_quantity > 0 ) { $html .= '<p class="already-in-cart">已加购:' . $cart_quantity . ' 件</p>'; } $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; }
你可以将上述代码添加到你当前使用的WordPress主题的functions.php文件中即可生效,也可以根据自己的需求调整已加购数量的HTML结构和样式类,匹配你的站点设计。
内容的提问来源于stack exchange,提问作者Shashank Sharma
相关产品推荐
相关产品推荐

