将数量字段添加到WooCommerce存档页面

在出售小物品的情况下,让我们说简单的钢笔,包括数量字段可以让客户轻松选择要订购的钢笔,而无需转到详细信息页面,这很有意义。

添加数量字段 #

由于WooCommerce没有将数量字段添加到存档页面的默认方法,因此我们创建了一个代码段供您使用,该代码段将立即生效。

在此代码段中,我们考虑了两点:

  • 它可以与AJAX添加到购物车按钮和普通的添加到购物车按钮一起使用
  • 它仅显示简单商品,不能将各种商品直接添加到购物车
  • 数量字段具有相对于最大订单金额的最大数量
  • 数量字段将仅显示是否可以实际购买产品(例如,没有价格意味着不能购买)。
  • 如果仅单独销售产品,则不会显示数量字段

如果要使用或仅测试代码片段,可以将以下内容复制到(子)主题的functions.php文件中。


/**
 * Add quantity field on the archive page.
 */
function custom_quantity_field_archive() {

	$product = wc_get_product( get_the_ID() );

	if ( ! $product->is_sold_individually() && 'variable' != $product->get_type() && $product->is_purchasable() ) {
		woocommerce_quantity_input( array( 'min_value' => 1, 'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity() ) );
	}

}
add_action( 'woocommerce_after_shop_loop_item', 'custom_quantity_field_archive', 0, 9 );


/**
 * Add requires JavaScript.
 */
function custom_add_to_cart_quantity_handler() {

	wc_enqueue_js( '
		jQuery( ".post-type-archive-product" ).on( "click", ".quantity input", function() {
			return false;
		});
		jQuery( ".post-type-archive-product" ).on( "change input", ".quantity .qty", function() {
			var add_to_cart_button = jQuery( this ).parents( ".product" ).find( ".add_to_cart_button" );
			// For AJAX add-to-cart actions
			add_to_cart_button.attr( "data-quantity", jQuery( this ).val() );
			// For non-AJAX add-to-cart actions
			add_to_cart_button.attr( "href", "?add-to-cart=" + add_to_cart_button.attr( "data-product_id" ) + "&quantity=" + jQuery( this ).val() );
		});
	' );

}
add_action( 'init', 'custom_add_to_cart_quantity_handler' );

添加代码段后,您应该立即看到更改(如果您使用某种缓存插件,则可能需要清除缓存)。

结果应如下所示:

在右侧添加数量字段 #

如果要在“添加到购物车”按钮的右侧添加数量字段,则可以搜索并替换以下行:


add_action( 'woocommerce_after_shop_loop_item', 'custom_quantity_field_archive', 0, 9 );


add_action( 'woocommerce_after_shop_loop_item', 'custom_quantity_field_archive', 15, 9 );

这将改变??0到??15这是优先级的改变,并确保数量字段按钮本身之后添加。现在页面将如下所示:

数量字段未对齐 #

数量字段可能无法与添加到购物车按钮完全对齐。在这种情况下,您可以将以下CSS添加到您的网站(此操作有多种方式;很多时候您的主题中都有一个选项,或者可以通过JetPack或Simple Custom CSS之类的插件来完成) 。


.archive .quantity { display: inline-block; }

如果觉得使用代码比较麻烦的话,也直接有插件可以使用:
https://wp101.net/plugins/quantity-field-on-shop-page-for-woocommerce/