默认情况下,woocommerce 可以通过 url 一次添加一个产品:
...购物车/?添加到购物车 = 12
默认情况下,如果不更改 WOcommerce 中的任何内容,您将无法通过按钮一次添加所有这些产品,您需要更改默认代码。
一个简单的解决方案是创建一个 wordpress 插件,添加通过 url 接受添加多个产品的功能,客户端只需添加这个 wordpress 插件,它就会工作。
我建议您在生产前创建一个本地环境进行测试。
文档链接:https://developer.wordpress.org/plugins/plugin-basics/
这是一个代码示例,您需要在 plugins 文件夹中创建一个文件夹并为其命名示例:首先是 my_plugin,然后在其中创建一个名为 my_plugin.php 的文件
在此文件中添加以下代码:
<?php
/**
* Plugin Name: YOUR PLUGIN NAME
*/
function woocommerce_maybe_add_multiple_products_to_cart() {
// Make sure WC is installed, and add-to-cart qauery arg exists, and contains at least one comma.
if ( ! class_exists( 'WC_Form_Handler' ) || empty( $_REQUEST['add-to-cart'] ) || false === strpos( $_REQUEST['add-to-cart'], ',' ) ) {
return;
}
// Remove WooCommerce's hook, as it's useless (doesn't handle multiple products).
remove_action( 'wp_loaded', array( 'WC_Form_Handler', 'add_to_cart_action' ), 20 );
$product_ids = explode( ',', $_REQUEST['add-to-cart'] );
$count = count( $product_ids );
$number = 0;
foreach ( $product_ids as $product_id ) {
if ( ++$number === $count ) {
// Ok, final item, let's send it back to woocommerce's add_to_cart_action method for handling.
$_REQUEST['add-to-cart'] = $product_id;
return WC_Form_Handler::add_to_cart_action();
}
$product_id = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $product_id ) );
$was_added_to_cart = false;
$adding_to_cart = wc_get_product( $product_id );
if ( ! $adding_to_cart ) {
continue;
}
$add_to_cart_handler = apply_filters( 'woocommerce_add_to_cart_handler', $adding_to_cart->product_type, $adding_to_cart );
/*
* Sorry.. if you want non-simple products, you're on your own.
*
* Related: WooCommerce has set the following methods as private:
* WC_Form_Handler::add_to_cart_handler_variable(),
* WC_Form_Handler::add_to_cart_handler_grouped(),
* WC_Form_Handler::add_to_cart_handler_simple()
*
* Why you gotta be like that WooCommerce?
*/
if ( 'simple' !== $add_to_cart_handler ) {
continue;
}
// For now, quantity applies to all products.. This could be changed easily enough, but I didn't need this feature.
$quantity = empty( $_REQUEST['quantity'] ) ? 1 : wc_stock_amount( $_REQUEST['quantity'] );
$passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity );
if ( $passed_validation && false !== WC()->cart->add_to_cart( $product_id, $quantity ) ) {
wc_add_to_cart_message( array( $product_id => $quantity ), true );
}
}
}
// Fire before the WC_Form_Handler::add_to_cart_action callback.
add_action( 'wp_loaded', 'woocommerce_maybe_add_multiple_products_to_cart', 15 );
有一点很重要,此代码只是一个示例,您可以从如下网址添加产品:http://shop.com/shop/cart/?add-to-cart=3001,3282 只需传递您要更新的产品 ID。
这个修改 woocommerce 并因此允许通过 url 进行各种产品的代码不是我开发的,我在下面的链接中以它为例:
Adding multiple items to WooCommerce cart at once
在此链接中,您将看到一些建议。我所做的只是提供一个可能有助于解决您的问题的灯。
开发一个不会更改客户端站点源代码的插件是最好的选择,如果出现问题或失败,只需禁用一切恢复正常;)
我希望我能在某些方面有所帮助。