Compare commits

...

7 Commits

Author SHA1 Message Date
tikkhun 24d1ee0a13 chore: ignore docs/产品/*.png 2025-11-06 18:18:48 +08:00
tikkhun ea1011b73b chore: update 2025-11-06 17:38:57 +08:00
tikkhun d6238c49ee docs(frontend): 将前端钩子注释翻译为中文 2025-11-06 17:26:47 +08:00
tikkhun eda86d4d68 docs(frontend): 将前端钩子设置的注释翻译为中文 2025-11-06 17:26:42 +08:00
tikkhun 1746bb5dd2 feat(前端): 重构混装产品前端逻辑并优化购物车处理
重构混装产品的前端逻辑,改用模板部分替换完整页面模板
优化购物车处理流程,实现容器与子项关联管理
移除旧版混装产品单页模板,新增全局混装表单模板
2025-11-06 17:26:36 +08:00
tikkhun 02d7cf85df feat: 实现混装产品前端交互逻辑并优化样式
添加前端JS逻辑实现混装产品数量验证和按钮状态控制
优化CSS间距和颜色样式,移除冗余代码
更新模板文件结构以更好兼容主题
将资源注册改为直接加载
2025-11-06 16:49:11 +08:00
tikkhun 26e076af1a feat: 实现混装产品卡片式布局及批量添加功能
- 新增卡片式布局模板替换原有表格形式
- 添加后台一键批量选择所有simple product功能
- 优化前端样式兼容性及交互体验
- 增加版本号管理及资源文件版本控制
- 重构前端逻辑提升代码可维护性
2025-11-06 15:36:08 +08:00
12 changed files with 559 additions and 259 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
# Ignore product PNG design/reference images in docs
docs/产品/*.png

View File

@ -6,3 +6,69 @@
.yoone-bundle-table th, .yoone-bundle-table td { border-bottom: 1px solid #eee; padding: 8px; } .yoone-bundle-table th, .yoone-bundle-table td { border-bottom: 1px solid #eee; padding: 8px; }
.yoone-bundle-meta { display: flex; gap: 1em; align-items: center; } .yoone-bundle-meta { display: flex; gap: 1em; align-items: center; }
.yoone-bundle-actions { margin-top: 1em; } .yoone-bundle-actions { margin-top: 1em; }
/* 在混装产品页面隐藏默认产品图片区域(兼容常见主题结构) */
.product.type-yoone_bundle div.images,
.single-product .product.type-yoone_bundle .images {
display: none !important;
}
/* 表格列宽优化 */
.yoone-bundle-table th:nth-child(3),
.yoone-bundle-table td:nth-child(3) { width: 160px; }
/* 强制混装产品页面的内容区域为全宽,以容纳卡片布局 */
.yoone-bundle-product-page .summary {
width: 100% !important; /* 覆盖主题默认的宽度限制 */
float: none !important; /* 清除浮动 */
}
.yoone-bundle-add-to-cart-button {
margin-top: 1em;
}
/* 新的卡片式布局样式 */
.yoone-bundle-items-wrapper {
display: flex;
flex-wrap: wrap;
gap: 1em;
margin: 1em;
}
.yoone-bundle-item-card {
display: flex;
flex-direction: column;
align-items: center; /* 垂直居中对齐 */
width: 150px; /* 卡片宽度,可根据需要调整 */
border: 1px solid #eee;
border-radius: 8px;
padding: 10px;
text-align: center;
transition: box-shadow 0.3s;
}
.yoone-bundle-item-card:hover {
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.yoone-bundle-item-card .item-image img {
max-width: 100%;
height: auto;
border-radius: 4px;
}
.yoone-bundle-item-card .item-title {
font-size: 14px;
margin: 8px 0;
font-weight: bold;
}
.yoone-bundle-item-card .item-price {
font-size: 16px;
margin-bottom: 8px;
}
.yoone-bundle-item-card .item-quantity input {
width: 80px;
text-align: center;
}

View File

@ -1,3 +1,52 @@
(function($) { (function($) {
// 预留:后台增强脚本(例如联动过滤 simple products、校验最小数量等 $(document).ready(function() {
// “一键添加所有 Simple Product” 按钮点击事件
$(document).on('click', '.yoone-add-all-simple-products', function(e) {
e.preventDefault();
var $button = $(this);
var $select = $('select.wc-product-search[name="yoone_bundle_allowed_products[]"]');
var nonce = $('#yoone_bundle_admin_nonce_field').val();
$button.prop('disabled', true).text('正在加载...');
$.ajax({
url: ajaxurl,
method: 'POST',
data: {
action: 'yoone_get_all_simple_products',
security: nonce
},
success: function(response) {
if (response.success) {
var existing_ids = $select.val() || [];
var products = response.data;
products.forEach(function(product) {
// 如果下拉列表中不存在该选项,则添加
if ($select.find('option[value="' + product.id + '"]').length === 0) {
var newOption = new Option(product.text, product.id, false, false);
$select.append(newOption);
}
// 将新获取的商品ID加入到已选中的ID数组中
if (existing_ids.indexOf(product.id.toString()) === -1) {
existing_ids.push(product.id.toString());
}
});
// 更新 select2 的选中状态
$select.val(existing_ids).trigger('change');
$button.prop('disabled', false).text('一键添加所有 Simple Product');
} else {
alert('加载失败,请重试。');
$button.prop('disabled', false).text('一键添加所有 Simple Product');
}
},
error: function() {
alert('请求失败,请检查网络连接或联系管理员。');
$button.prop('disabled', false).text('一键添加所有 Simple Product');
}
});
});
});
})(jQuery); })(jQuery);

View File

@ -1,3 +1,45 @@
(function($) { (function($) {
// 预留:如需在前端动态计算价格或增强交互,可在此添加脚本。 'use strict';
$(function() {
var minQty = 0;
var wrapper = $('.yoone-bundle-form');
// 从 DOM 中获取最小数量
var minText = wrapper.find('.yoone-bundle-min').text();
if (minText) {
var match = minText.match(/\d+/);
if (match) {
minQty = parseInt(match[0], 10);
}
}
function updateState() {
var total = 0;
wrapper.find('.yoone-bundle-qty').each(function() {
var v = parseInt($(this).val(), 10);
if (!isNaN(v) && v > 0) {
total += v;
}
});
// 更新显示的数量
wrapper.find('.yoone-bundle-selected-count').text(total);
// 根据是否满足最小数量来启用/禁用按钮
var btn = wrapper.find('.single_add_to_cart_button');
if (total >= minQty) {
btn.prop('disabled', false);
} else {
btn.prop('disabled', true);
}
}
// 绑定事件
wrapper.on('change keyup', '.yoone-bundle-qty', updateState);
// 页面加载时立即执行一次,以确保初始状态正确
updateState();
});
})(jQuery); })(jQuery);

1
docs/需求.md Normal file
View File

@ -0,0 +1 @@
- 混装产品可批量添加simple product为混装可选商品

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* 后台:为混装产品提供配置界面(可混装商品、最小数量、分类)。 * Admin: Provides the configuration interface for bundle products (allowed products, min quantity, categories).
*/ */
defined('ABSPATH') || exit; defined('ABSPATH') || exit;
@ -19,13 +19,18 @@ class Yoone_Product_Bundles_Admin {
add_action('woocommerce_product_data_panels', array($this, 'render_product_data_panel')); add_action('woocommerce_product_data_panels', array($this, 'render_product_data_panel'));
// 保存配置 // 保存配置
add_action('woocommerce_admin_process_product_meta', array($this, 'save_product_meta')); add_action('woocommerce_admin_process_product_meta', array($this, 'save_product_meta'));
add_action('woocommerce_process_product_meta', array($this, 'save_product_meta'));
add_action('save_post_product', array($this, 'save_product_meta'), 15);
// AJAX: 获取所有 simple product
add_action('wp_ajax_yoone_get_all_simple_products', array($this, 'ajax_get_all_simple_products'));
} }
public function add_product_data_tab($tabs) { public function add_product_data_tab($tabs) {
$tabs['yoone_bundle'] = array( $tabs['yoone_bundle'] = array(
'label' => __('混装产品', 'yoone-product-bundles'), 'label' => __('Mix and Match', 'yoone-product-bundles'),
'target' => 'yoone_bundle_data', 'target' => 'yoone_bundle_data',
'class' => array('show_if_yoone_bundle'), // 仅当类型为 yoone_bundle 时显示 'class' => array('show_if_yoone_bundle'), // Only show for 'yoone_bundle' type
'priority' => 70, 'priority' => 70,
); );
return $tabs; return $tabs;
@ -39,13 +44,17 @@ class Yoone_Product_Bundles_Admin {
$min_qty = $config['min_qty']; $min_qty = $config['min_qty'];
$cats = $config['categories']; $cats = $config['categories'];
echo '<div id="yoone_bundle_data" class="panel woocommerce_options_panel hidden">'; echo '<div id="yoone_bundle_data" class="panel woocommerce_options_panel show_if_yoone_bundle">';
echo '<div class="options_group">'; wp_nonce_field('yoone-bundle-admin-nonce', 'yoone_bundle_admin_nonce_field');
echo '<p>' . esc_html__('配置可混装的简单商品、最小混装数量以及前端展示的分类分组。', 'yoone-product-bundles') . '</p>';
// 可混装商品:使用 Woo 的产品搜索select2multiple echo '<div class="options_group">';
echo '<p class="form-field"><label>' . esc_html__('可混装商品', 'yoone-product-bundles') . '</label>'; echo '<p>' . esc_html__('Configure the simple products that can be included in the bundle, the minimum quantity, and the category grouping for the frontend display.', 'yoone-product-bundles') . '</p>';
echo '<select class="wc-product-search" multiple style="width: 90%;" name="yoone_bundle_allowed_products[]" data-placeholder="' . esc_attr__('选择可混装的简单商品…', 'yoone-product-bundles') . '" data-action="woocommerce_json_search_products_and_variations">';
// Allowed products: use Woo's product search (select2), multiple
echo '<p class="form-field"><label>' . esc_html__('Allowed Products', 'yoone-product-bundles') . '</label>';
echo '<button type="button" class="button yoone-add-all-simple-products" style="margin-left: 10px;">' . esc_html__('Add All Simple Products', 'yoone-product-bundles') . '</button>';
// Search only for products, not variations, to avoid errors
echo '<select class="wc-product-search" multiple style="width: 90%;" name="yoone_bundle_allowed_products[]" data-placeholder="' . esc_attr__('Search for simple products…', 'yoone-product-bundles') . '" data-action="woocommerce_json_search_products">';
if (! empty($allowed)) { if (! empty($allowed)) {
foreach ($allowed as $pid) { foreach ($allowed as $pid) {
$p = wc_get_product($pid); $p = wc_get_product($pid);
@ -55,30 +64,30 @@ class Yoone_Product_Bundles_Admin {
} }
} }
echo '</select>'; echo '</select>';
echo '<span class="description">' . esc_html__('仅支持 simple product变体商品可在后续版本支持。', 'yoone-product-bundles') . '</span>'; echo '<span class="description">' . esc_html__('Only simple products are supported. Variable products may be supported in a future version.', 'yoone-product-bundles') . '</span>';
echo '</p>'; echo '</p>';
// 最小混装数量 // Minimum bundle quantity
woocommerce_wp_text_input(array( woocommerce_wp_text_input(array(
'id' => 'yoone_bundle_min_quantity', 'id' => 'yoone_bundle_min_quantity',
'label' => __('最小混装数量', 'yoone-product-bundles'), 'label' => __('Minimum Quantity', 'yoone-product-bundles'),
'type' => 'number', 'type' => 'number',
'desc_tip' => true, 'desc_tip' => true,
'description' => __('顾客选择的总数量需不小于该值,方可加入购物车。', 'yoone-product-bundles'), 'description' => __('The total quantity of selected items must be greater than or equal to this value to add to the cart.', 'yoone-product-bundles'),
'value' => $min_qty, 'value' => $min_qty,
'custom_attributes' => array('min' => '0'), 'custom_attributes' => array('min' => '0'),
)); ));
// 展示分类product_cat // Display categories (product_cat)
echo '<p class="form-field"><label>' . esc_html__('前端展示分类', 'yoone-product-bundles') . '</label>'; echo '<p class="form-field"><label>' . esc_html__('Display Categories', 'yoone-product-bundles') . '</label>';
echo '<select class="wc-enhanced-select" multiple style="width: 90%;" name="yoone_bundle_categories[]" data-placeholder="' . esc_attr__('选择用于分组展示的分类…', 'yoone-product-bundles') . '">'; echo '<select class="wc-enhanced-select" multiple style="width: 90%;" name="yoone_bundle_categories[]" data-placeholder="' . esc_attr__('Select categories to group products by…', 'yoone-product-bundles') . '">';
$terms = get_terms(array('taxonomy' => 'product_cat', 'hide_empty' => false)); $terms = get_terms(array('taxonomy' => 'product_cat', 'hide_empty' => false));
foreach ($terms as $t) { foreach ($terms as $t) {
$selected = in_array($t->term_id, $cats, true) ? 'selected' : ''; $selected = in_array($t->term_id, $cats, true) ? 'selected' : '';
printf('<option value="%d" %s>%s</option>', $t->term_id, $selected, esc_html($t->name)); printf('<option value="%d" %s>%s</option>', $t->term_id, $selected, esc_html($t->name));
} }
echo '</select>'; echo '</select>';
echo '<span class="description">' . esc_html__('用于在前端页面按分类分组展示可混装商品(仅展示与所选分类匹配的可混装商品)。', 'yoone-product-bundles') . '</span>'; echo '<span class="description">' . esc_html__('Group the allowed products by category on the frontend. Only products matching the selected categories will be shown.', 'yoone-product-bundles') . '</span>';
echo '</p>'; echo '</p>';
echo '</div>'; // options_group echo '</div>'; // options_group
@ -86,12 +95,25 @@ class Yoone_Product_Bundles_Admin {
} }
public function save_product_meta($post_id) { public function save_product_meta($post_id) {
$product = wc_get_product($post_id); // 无论当前 product 对象类型为何,只要提交了我们的字段,就进行保存。
if (! $product || $product->get_type() !== Yoone_Product_Bundles::TYPE) return; // 这可以避免在首次切换产品类型时由于保存顺序问题导致配置未写入。
$has_fields = isset($_POST['yoone_bundle_allowed_products']) || isset($_POST['yoone_bundle_min_quantity']) || isset($_POST['yoone_bundle_categories']);
if (! $has_fields) return;
// 保存 allowed products // 保存 allowed products
$allowed = isset($_POST['yoone_bundle_allowed_products']) ? (array) $_POST['yoone_bundle_allowed_products'] : array(); $allowed = isset($_POST['yoone_bundle_allowed_products']) ? (array) $_POST['yoone_bundle_allowed_products'] : array();
$allowed = array_values(array_filter(array_map('absint', $allowed))); $allowed = array_values(array_filter(array_map('absint', $allowed)));
// 仅保留 simple 产品ID
if (! empty($allowed)) {
$simple_only = array();
foreach ($allowed as $aid) {
$p = wc_get_product($aid);
if ($p && $p->is_type('simple')) {
$simple_only[] = $aid;
}
}
$allowed = $simple_only;
}
update_post_meta($post_id, Yoone_Product_Bundles::META_ALLOWED_PRODUCTS, $allowed); update_post_meta($post_id, Yoone_Product_Bundles::META_ALLOWED_PRODUCTS, $allowed);
// 保存 min qty // 保存 min qty
@ -103,4 +125,30 @@ class Yoone_Product_Bundles_Admin {
$cats = array_values(array_filter(array_map('absint', $cats))); $cats = array_values(array_filter(array_map('absint', $cats)));
update_post_meta($post_id, Yoone_Product_Bundles::META_CATEGORIES, $cats); update_post_meta($post_id, Yoone_Product_Bundles::META_CATEGORIES, $cats);
} }
/**
* AJAX handler: 获取所有已发布的 simple product
*/
public function ajax_get_all_simple_products() {
if (! current_user_can('edit_products')) {
wp_send_json_error('permission_denied', 403);
}
check_ajax_referer('yoone-bundle-admin-nonce', 'security');
$products = wc_get_products(array(
'type' => 'simple',
'status' => 'publish',
'limit' => -1,
));
$results = array();
foreach ($products as $product) {
$results[] = array(
'id' => $product->get_id(),
'text' => $product->get_formatted_name(),
);
}
wp_send_json_success($results);
}
} }

View File

@ -1,13 +1,13 @@
<?php <?php
/** /**
* 核心:注册产品类型、常量、工具方法。 * Core: Registers the product type, constants, and utility methods.
*/ */
defined('ABSPATH') || exit; defined('ABSPATH') || exit;
class Yoone_Product_Bundles { class Yoone_Product_Bundles {
const TYPE = 'yoone_bundle'; const TYPE = 'yoone_bundle';
// 配置的 postmeta 键名 // Post meta keys for configuration
const META_ALLOWED_PRODUCTS = '_yoone_bundle_allowed_products'; // array<int> const META_ALLOWED_PRODUCTS = '_yoone_bundle_allowed_products'; // array<int>
const META_MIN_QTY = '_yoone_bundle_min_quantity'; // int const META_MIN_QTY = '_yoone_bundle_min_quantity'; // int
const META_CATEGORIES = '_yoone_bundle_categories'; // array<int> product_cat term_ids const META_CATEGORIES = '_yoone_bundle_categories'; // array<int> product_cat term_ids
@ -22,22 +22,22 @@ class Yoone_Product_Bundles {
} }
private function __construct() { private function __construct() {
// 将产品类型加入选择器 // Add "Mix and Match" to the "Product Type" dropdown in the admin.
add_filter('product_type_selector', array($this, 'register_product_type_in_selector')); add_filter('product_type_selector', array($this, 'register_product_type_in_selector'));
// 将类型映射到我们的 WC_Product 派生类 // Map the type to our class name, so WooCommerce instantiates the correct product object.
add_filter('woocommerce_product_class', array($this, 'map_product_class'), 10, 2); add_filter('woocommerce_product_class', array($this, 'map_product_class'), 10, 2);
} }
/** /**
* 在后台“产品类型”下拉中添加“混装产品”。 * Add "Mix and Match" to the "Product Type" dropdown in the admin.
*/ */
public function register_product_type_in_selector($types) { public function register_product_type_in_selector($types) {
$types[self::TYPE] = __('混装产品 (Yoone Bundle)', 'yoone-product-bundles'); $types[self::TYPE] = __('Mix and Match (Yoone Bundle)', 'yoone-product-bundles');
return $types; return $types;
} }
/** /**
* 将类型映射到类名WooCommerce 会实例化对应产品对象。 * Map the type to our class name, so WooCommerce instantiates the correct product object.
*/ */
public function map_product_class($classname, $product_type) { public function map_product_class($classname, $product_type) {
if ($product_type === self::TYPE) { if ($product_type === self::TYPE) {
@ -47,7 +47,7 @@ class Yoone_Product_Bundles {
} }
/** /**
* 读取并规范化 bundle 配置。 * Read and normalize the bundle configuration.
* @param int|WC_Product $product * @param int|WC_Product $product
* @return array{allowed_products:int[],min_qty:int,categories:int[]} * @return array{allowed_products:int[],min_qty:int,categories:int[]}
*/ */
@ -58,7 +58,18 @@ class Yoone_Product_Bundles {
$allowed = get_post_meta($pid, self::META_ALLOWED_PRODUCTS, true); $allowed = get_post_meta($pid, self::META_ALLOWED_PRODUCTS, true);
$min = absint(get_post_meta($pid, self::META_MIN_QTY, true)); $min = absint(get_post_meta($pid, self::META_MIN_QTY, true));
$cats = get_post_meta($pid, self::META_CATEGORIES, true); $cats = get_post_meta($pid, self::META_CATEGORIES, true);
// Keep only simple products (to avoid issues if variations or other types were selected in the backend)
$allowed = is_array($allowed) ? array_values(array_map('absint', $allowed)) : array(); $allowed = is_array($allowed) ? array_values(array_map('absint', $allowed)) : array();
if (! empty($allowed)) {
$simple_only = array();
foreach ($allowed as $aid) {
$p = wc_get_product($aid);
if ($p && $p->is_type('simple')) {
$simple_only[] = $aid;
}
}
$allowed = $simple_only;
}
$cats = is_array($cats) ? array_values(array_map('absint', $cats)) : array(); $cats = is_array($cats) ? array_values(array_map('absint', $cats)) : array();
return array( return array(
'allowed_products' => $allowed, 'allowed_products' => $allowed,

View File

@ -1,15 +1,16 @@
<?php <?php
/** /**
* 产品类型对象:WC_Product_Yoone_Bundle * Product Type Object: WC_Product_Yoone_Bundle
* - 定义产品类型标识; * - Defines the product type identifier;
* - 可选择设置为售卖方式(例如仅允许单件购买)。 * - Can be configured to set purchasing rules (e.g., sold individually).
*/ */
defined('ABSPATH') || exit; defined('ABSPATH') || exit;
class WC_Product_Yoone_Bundle extends WC_Product { class WC_Product_Yoone_Bundle extends WC_Product {
public function __construct($product) { public function __construct($product) {
parent::__construct($product); parent::__construct($product);
$this->set_virtual(true); // 混装产品不作为单独实物发货实际发货明细由所选组件决定MVP 简化) // A bundle product itself isn't shipped; shipping is determined by its components (MVP simplification).
$this->set_virtual(true);
} }
public function get_type() { public function get_type() {
@ -17,9 +18,35 @@ class WC_Product_Yoone_Bundle extends WC_Product {
} }
/** /**
* 混装产品通常只允许单件购买(其内部包含多个组件)。 * Bundle products are typically sold individually as they contain multiple items.
*/ */
public function is_sold_individually() { public function is_sold_individually() {
return true; return true;
} }
// --- Price Override ---
public function get_price($context = 'view') {
return 0;
}
public function get_regular_price($context = 'view') {
return 0;
}
public function get_sale_price($context = 'view') {
return 0;
}
public function set_price($price) {
// Prevent price from being changed.
}
public function set_regular_price($price) {
// Prevent price from being changed.
}
public function set_sale_price($price) {
// Prevent price from being changed.
}
} }

View File

@ -1,102 +1,161 @@
<?php <?php
/** /**
* 前端:渲染混装产品的自定义 add-to-cart 表单、校验并加入购物车 * 前端:为混装产品渲染自定义的“添加到购物车”表单,并处理验证和加入购物车的逻辑
*/ */
defined('ABSPATH') || exit; defined('ABSPATH') || exit;
class Yoone_Product_Bundles_Frontend { class Yoone_Product_Bundles_Frontend {
protected static $instance = null;
private static $_instance = null;
public static function instance() { public static function instance() {
if (null === self::$instance) self::$instance = new self(); if (is_null(self::$_instance)) {
return self::$instance; self::$_instance = new self();
}
return self::$_instance;
} }
private function __construct() { private function __construct() {
// 用我们的模板替换默认的 add-to-cart 按钮 $this->setup_hooks();
add_action('woocommerce_' . Yoone_Product_Bundles::TYPE . '_add_to_cart', array($this, 'render_add_to_cart')); // 显示表单
// 处理加入购物车:校验数量并打包所选组件数据
add_filter('woocommerce_add_to_cart_validation', array($this, 'validate_add_to_cart'), 10, 6);
add_filter('woocommerce_add_cart_item_data', array($this, 'add_cart_item_data'), 10, 3);
// 在购物车/订单中显示组件摘要
add_filter('woocommerce_get_item_data', array($this, 'display_cart_item_data'), 10, 2);
// 结算前动态调整价格
add_action('woocommerce_before_calculate_totals', array($this, 'adjust_bundle_price'), 20, 1);
} }
/** /**
* 渲染自定义表单:按所选分类分组显示允许的简单商品,提供数量输入 * 设置所有与前端相关的钩子。
*/ */
public function render_add_to_cart() { public function setup_hooks() {
wc_get_template('single-product/add-to-cart/yoone-bundle.php', array(), '', YOONE_PB_PATH . 'templates/'); // 处理混装产品的自定义“添加到购物车”流程
add_filter('woocommerce_add_to_cart_validation', array($this, 'process_bundle_add_to_cart'), 10, 3);
// 当混装容器被移除时,移除其子项目
add_action('woocommerce_cart_item_removed', array($this, 'remove_bundle_children'), 10, 2);
// 隐藏购物车中子项目的“移除”链接
add_filter('woocommerce_cart_item_remove_link', array($this, 'hide_child_remove_link'), 10, 2);
// 在购物车中,显示子项目所属的混装产品
add_filter('woocommerce_get_item_data', array($this, 'display_child_bundle_link'), 10, 2);
// 为混装产品页面添加 body class以便于样式化
add_filter('body_class', array($this, 'filter_body_class'));
// 用我们的自定义表单替换默认的“添加到购物车”按钮
add_action('woocommerce_single_product_summary', array($this, 'remove_default_add_to_cart_for_bundle'), 29);
add_action('woocommerce_single_product_summary', array($this, 'render_bundle_add_to_cart_form'), 30);
} }
/** /**
* 校验:总选择数量 >= min_qty * 劫持混装产品的“添加到购物车”流程。
* 验证提交,然后将容器和所有子产品添加到购物车。
*
* @return bool False 以阻止默认的“添加到购物车”操作。
*/ */
public function validate_add_to_cart($passed, $product_id, $quantity, $variation_id, $variations, $cart_item_data) { public function process_bundle_add_to_cart($passed, $product_id, $quantity) {
$product = wc_get_product($product_id); $product = wc_get_product($product_id);
if (! $product || $product->get_type() !== Yoone_Product_Bundles::TYPE) return $passed; if (!$product || $product->get_type() !== Yoone_Product_Bundles::TYPE) {
return $passed; // 不是我们的产品,直接通过。
$config = Yoone_Product_Bundles::get_bundle_config($product);
$min = max(0, absint($config['min_qty']));
// 从 POST 中收集数量
$selected = isset($_POST['yoone_bundle_components']) ? (array) $_POST['yoone_bundle_components'] : array();
$total_qty = 0;
foreach ($selected as $pid => $qty) {
$qty = absint($qty);
if ($qty > 0) $total_qty += $qty;
} }
if ($total_qty < $min) { // 1. 验证
wc_add_notice(sprintf(__('请至少选择 %d 件混装组件后再加入购物车。', 'yoone-product-bundles'), $min), 'error'); $config = Yoone_Product_Bundles::get_bundle_config($product);
$min_qty = max(1, absint($config['min_qty']));
$components = !empty($_POST['yoone_bundle_components']) ? (array) $_POST['yoone_bundle_components'] : array();
$total_qty = 0;
$clean_components = array();
foreach ($components as $comp_id => $qty) {
$qty = absint($qty);
if ($qty > 0) {
$total_qty += $qty;
$clean_components[absint($comp_id)] = $qty;
}
}
if ($total_qty < $min_qty) {
wc_add_notice(sprintf(__('You need to select at least %d items to add this bundle to your cart.', 'yoone-product-bundles'), $min_qty), 'error');
return false; return false;
} }
return $passed;
// 2. 添加商品到购物车
try {
$bundle_container_id = uniqid('bundle_');
// 添加主混装产品作为价格为0的容器
WC()->cart->add_to_cart($product_id, 1, 0, array(), array('yoone_bundle_container_id' => $bundle_container_id));
// 添加子组件
foreach ($clean_components as $comp_id => $qty) {
WC()->cart->add_to_cart($comp_id, $qty, 0, array(), array(
'yoone_bundle_parent_id' => $bundle_container_id,
'yoone_bundle_parent_product_id' => $product_id
));
}
// 设置成功消息并重定向
wc_add_to_cart_message(array($product_id => 1), true);
add_filter('woocommerce_add_to_cart_redirect', function() { return wc_get_cart_url(); });
} catch (Exception $e) {
wc_add_notice($e->getMessage(), 'error');
return false;
}
// 阻止主产品的默认“添加到购物车”行为
return false;
} }
/** /**
* 将所选组件数据存入购物车项。 * 当一个购物车项目被移除时,检查它是否是一个混装容器。
* 如果是,则找到并移除其所有的子项目。
*/ */
public function add_cart_item_data($cart_item_data, $product_id, $variation_id) { public function remove_bundle_children($removed_cart_item_key, $cart) {
$product = wc_get_product($product_id); // 此钩子在项目已从购物车会话中移除后触发,所以我们在 `removed_cart_contents` 中查找它。
if (! $product || $product->get_type() !== Yoone_Product_Bundles::TYPE) return $cart_item_data; if (!isset($cart->removed_cart_contents[$removed_cart_item_key])) {
return;
}
$selected = isset($_POST['yoone_bundle_components']) ? (array) $_POST['yoone_bundle_components'] : array(); $removed_item = $cart->removed_cart_contents[$removed_cart_item_key];
// 仅保留大于 0 的数量
$components = array(); // 检查被移除的商品是否是我们的混装容器。
foreach ($selected as $pid => $qty) { if (isset($removed_item['yoone_bundle_container_id'])) {
$pid = absint($pid); $bundle_container_id = $removed_item['yoone_bundle_container_id'];
$qty = absint($qty); $child_item_keys_to_remove = [];
if ($pid && $qty > 0) $components[$pid] = $qty;
// 遍历购物车,找到所有属于此容器的子项目。
// 我们不能在遍历时直接修改购物车所以我们先收集要移除的项目的key。
foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
if (isset($cart_item['yoone_bundle_parent_id']) && $cart_item['yoone_bundle_parent_id'] === $bundle_container_id) {
$child_item_keys_to_remove[] = $cart_item_key;
}
}
// 现在遍历收集到的key并从购物车中移除子项目。
foreach ($child_item_keys_to_remove as $key_to_remove) {
$cart->remove_cart_item($key_to_remove);
} }
if (! empty($components)) {
$cart_item_data['yoone_bundle_components'] = $components;
} }
return $cart_item_data;
} }
/** /**
* 在购物车行项目中展示所选组件摘要。 * 隐藏混装产品子项目的移除链接
*/ */
public function display_cart_item_data($item_data, $cart_item) { public function hide_child_remove_link($link, $cart_item_key) {
if (! empty($cart_item['yoone_bundle_components'])) { $cart_item = WC()->cart->get_cart_item($cart_item_key);
$lines = array(); if (isset($cart_item['yoone_bundle_parent_id'])) {
foreach ($cart_item['yoone_bundle_components'] as $pid => $qty) { return '';
$p = wc_get_product($pid);
if ($p) {
$lines[] = sprintf('%s × %d', $p->get_name(), $qty);
} }
return $link;
} }
if (! empty($lines)) {
/**
* 对于子项目,在购物车中添加一个元信息行,以链接回父混装产品。
*/
public function display_child_bundle_link($item_data, $cart_item) {
if (isset($cart_item['yoone_bundle_parent_product_id'])) {
$parent_product = wc_get_product($cart_item['yoone_bundle_parent_product_id']);
if ($parent_product) {
$item_data[] = array( $item_data[] = array(
'key' => __('混装内容', 'yoone-product-bundles'), 'key' => __('Part of', 'yoone-product-bundles'),
'value' => implode("\n", $lines), 'value' => $parent_product->get_name(),
'display' => implode('<br/>', array_map('esc_html', $lines)),
); );
} }
} }
@ -104,30 +163,36 @@ class Yoone_Product_Bundles_Frontend {
} }
/** /**
* 结算前根据组件动态调整混装产品的行项目价格(= 所选简单商品单价 × 数量 的总和)。 * 仅为混装产品移除默认的“添加到购物车”按钮。
* 注意:这里使用的是产品当前价格(不含税的基础价),是否包含税由 WooCommerce 税设置决定。
*/ */
public function adjust_bundle_price($cart) { public function remove_default_add_to_cart_for_bundle() {
if (is_admin() && ! defined('DOING_AJAX')) { global $product;
return; // 后台不处理 if ($product && $product->get_type() === Yoone_Product_Bundles::TYPE) {
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30);
}
} }
if (empty($cart) || ! method_exists($cart, 'get_cart')) return;
foreach ($cart->get_cart() as $cart_item_key => $cart_item) { /**
if (empty($cart_item['yoone_bundle_components'])) continue; * 为混装产品渲染自定义的“添加到购物车”表单。
$product = isset($cart_item['data']) ? $cart_item['data'] : null; */
if (! $product || ! is_a($product, 'WC_Product')) continue; public function render_bundle_add_to_cart_form() {
if ($product->get_type() !== Yoone_Product_Bundles::TYPE) continue; global $product;
if ($product && $product->get_type() === Yoone_Product_Bundles::TYPE) {
wc_get_template('global/yoone-bundle-form.php', array(), '', YOONE_PB_PATH . 'templates/');
}
}
$total = 0.0; /**
foreach ($cart_item['yoone_bundle_components'] as $pid => $qty) { * 为混装产品页面添加一个 body class。
$p = wc_get_product($pid); */
if (! $p) continue; public function filter_body_class($classes) {
$unit = floatval($p->get_price()); // 基础价 global $post;
$total += $unit * absint($qty); if (is_singular('product') && $post) {
} $product = wc_get_product($post->ID);
// 将产品行项目价格设为总价 if ($product && $product->get_type() === Yoone_Product_Bundles::TYPE) {
$product->set_price($total); $classes[] = 'yoone-bundle-product';
} }
} }
return $classes;
}
} }

View File

@ -0,0 +1,110 @@
<?php
/**
* Yoone Product Bundles - Mix and Match Product Selection Form
*
* This template part contains the full frontend interface for selecting bundle components,
* including the card-based layout, quantity inputs, and dynamically updated total count.
* It is hooked into `woocommerce_single_product_summary` to replace the standard add-to-cart form.
*
* @version 3.0.1
*/
defined('ABSPATH') || exit;
global $product;
// --- 数据准备逻辑 ---
$config = Yoone_Product_Bundles::get_bundle_config($product);
$allowed = $config['allowed_products'];
$min_qty = max(0, absint($config['min_qty']));
$cat_ids = $config['categories'];
$allowed_products = array();
foreach ($allowed as $pid) {
$p = wc_get_product($pid);
if ($p && $p->is_type('simple')) {
$allowed_products[$pid] = $p;
}
}
$groups = array();
if (!empty($cat_ids)) {
$others = array();
foreach ($allowed_products as $pid => $p) {
$terms = get_the_terms($pid, 'product_cat');
$matched = false;
if (is_array($terms)) {
foreach ($terms as $t) {
if (in_array($t->term_id, $cat_ids, true)) {
if (!isset($groups[$t->term_id])) {
$groups[$t->term_id] = array('term' => $t, 'items' => array());
}
$groups[$t->term_id]['items'][] = $p;
$matched = true;
}
}
}
if (!$matched) $others[] = $p;
}
if (!empty($others)) $groups[0] = array('term' => null, 'items' => $others);
} else {
$groups[0] = array('term' => null, 'items' => array_values($allowed_products));
}
// --- 数据准备逻辑结束 ---
?>
<div class="yoone-bundle-form-container">
<form class="cart yoone-bundle-form" action="<?php echo esc_url(apply_filters('woocommerce_add_to_cart_form_action', $product->get_permalink())); ?>" method="post" enctype="multipart/form-data">
<div class="yoone-bundle-meta">
<p class="yoone-bundle-min"><?php printf(esc_html__('Select at least %d items to build your bundle.', 'yoone-product-bundles'), $min_qty); ?></p>
<p class="yoone-bundle-selected"><?php esc_html_e('Currently selected:', 'yoone-product-bundles'); ?> <span class="yoone-bundle-selected-count">0</span></p>
<div class="yoone-bundle-actions">
<input type="hidden" name="add-to-cart" value="<?php echo esc_attr($product->get_id()); ?>" />
<button type="submit" class="single_add_to_cart_button button alt" disabled><?php esc_html_e('Add to Cart', 'yoone-product-bundles'); ?></button>
</div>
</div>
<?php if (empty($allowed_products)) : ?>
<p><?php esc_html_e('No products are available for this bundle. Please configure it in the backend.', 'yoone-product-bundles'); ?></p>
<?php else : ?>
<?php foreach ($groups as $gid => $group) : ?>
<div class="yoone-bundle-group">
<?php if (!empty($group['term'])) : ?>
<h3 class="yoone-bundle-group-title"><?php echo esc_html($group['term']->name); ?></h3>
<?php else : ?>
<h3 class="yoone-bundle-group-title"><?php esc_html_e('Available Products', 'yoone-product-bundles'); ?></h3>
<?php endif; ?>
<?php if (empty($group['items'])) : ?>
<p class="yoone-bundle-no-items"><?php esc_html_e('No products available in this group.', 'yoone-product-bundles'); ?></p>
<?php else : ?>
<div class="yoone-bundle-items-wrapper">
<?php foreach ($group['items'] as $item) : ?>
<?php
$pid = $item->get_id();
$thumbnail = $item->get_image('woocommerce_thumbnail');
?>
<div class="yoone-bundle-item-card">
<div class="item-image">
<a href="<?php echo esc_url(get_permalink($pid)); ?>" target="_blank">
<?php echo $thumbnail ? $thumbnail : wc_placeholder_img('woocommerce_thumbnail'); ?>
</a>
</div>
<h4 class="item-title">
<a href="<?php echo esc_url(get_permalink($pid)); ?>" target="_blank"><?php echo esc_html($item->get_name()); ?></a>
</h4>
<div class="item-price">
<?php echo wp_kses_post($item->get_price_html()); ?>
</div>
<div class="item-quantity">
<input type="number" min="0" step="1" class="yoone-bundle-qty" name="yoone_bundle_components[<?php echo esc_attr($pid); ?>]" value="0" placeholder="0" />
</div>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
<?php endforeach; ?>
<?php endif; ?>
</form>
</div>

View File

@ -1,125 +0,0 @@
<?php
/**
* 模板:单个混装产品的 add-to-cart 表单
* 路径templates/single-product/add-to-cart/yoone-bundle.php
*/
defined('ABSPATH') || exit;
global $product;
if (! $product || $product->get_type() !== Yoone_Product_Bundles::TYPE) {
return;
}
$config = Yoone_Product_Bundles::get_bundle_config($product);
$allowed = $config['allowed_products'];
$min_qty = max(0, absint($config['min_qty']));
$cat_ids = $config['categories'];
// 收集允许的商品对象,且必须是 simple product
$allowed_products = array();
foreach ($allowed as $pid) {
$p = wc_get_product($pid);
if ($p && $p->is_type('simple')) {
$allowed_products[$pid] = $p;
}
}
// 按分类分组(如果未配置分类,则全部在一个组内)
$groups = array();
if (! empty($cat_ids)) {
foreach ($allowed_products as $pid => $p) {
$terms = get_the_terms($pid, 'product_cat');
$matched = false;
if (is_array($terms)) {
foreach ($terms as $t) {
if (in_array($t->term_id, $cat_ids, true)) {
$groups[$t->term_id]['term'] = $t;
$groups[$t->term_id]['items'][] = $p;
$matched = true;
}
}
}
// 若商品不属于所选分类,则不显示
if (! $matched) {
// 跳过
}
}
} else {
$groups[0] = array('term' => null, 'items' => array_values($allowed_products));
}
// 表单开始
?>
<form class="cart yoone-bundle-form" action="<?php echo esc_url( apply_filters( 'woocommerce_add_to_cart_form_action', $product->get_permalink() ) ); ?>" method="post" enctype="multipart/form-data">
<div class="yoone-bundle-meta">
<p class="yoone-bundle-min"><?php printf( esc_html__('至少选择 %d 件混装组件', 'yoone-product-bundles'), $min_qty ); ?></p>
<p class="yoone-bundle-selected"><?php esc_html_e('当前选择数量:', 'yoone-product-bundles'); ?><span class="yoone-bundle-selected-count">0</span></p>
</div>
<?php if (empty($groups)) : ?>
<p><?php esc_html_e('暂无可混装商品,请在后台为该混装产品配置。', 'yoone-product-bundles'); ?></p>
<?php else : ?>
<?php foreach ($groups as $gid => $group) : ?>
<div class="yoone-bundle-group">
<?php if (! empty($group['term'])) : ?>
<h3 class="yoone-bundle-group-title"><?php echo esc_html($group['term']->name); ?></h3>
<?php else : ?>
<h3 class="yoone-bundle-group-title"><?php esc_html_e('可混装商品', 'yoone-product-bundles'); ?></h3>
<?php endif; ?>
<table class="yoone-bundle-table">
<thead>
<tr>
<th><?php esc_html_e('商品', 'yoone-product-bundles'); ?></th>
<th><?php esc_html_e('价格', 'yoone-product-bundles'); ?></th>
<th style="width:140px;"><?php esc_html_e('数量', 'yoone-product-bundles'); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($group['items'] as $item) : ?>
<?php $pid = $item->get_id(); ?>
<tr>
<td>
<a href="<?php echo esc_url(get_permalink($pid)); ?>" target="_blank"><?php echo esc_html($item->get_name()); ?></a>
</td>
<td>
<?php echo wp_kses_post($item->get_price_html()); ?>
</td>
<td>
<input type="number" min="0" step="1" class="yoone-bundle-qty" name="yoone_bundle_components[<?php echo esc_attr($pid); ?>]" value="0" />
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endforeach; ?>
<?php endif; ?>
<div class="yoone-bundle-actions">
<input type="hidden" name="add-to-cart" value="<?php echo esc_attr($product->get_id()); ?>" />
<button type="submit" class="single_add_to_cart_button button alt" disabled><?php esc_html_e('加入购物车', 'yoone-product-bundles'); ?></button>
</div>
</form>
<script>
(function($){
function updateState(){
var total = 0;
$('.yoone-bundle-qty').each(function(){
var v = parseInt($(this).val(), 10);
if (!isNaN(v) && v > 0) total += v;
});
$('.yoone-bundle-selected-count').text(total);
var min = <?php echo (int) $min_qty; ?>;
var btn = $('.yoone-bundle-actions .single_add_to_cart_button');
if (total >= min) {
btn.prop('disabled', false);
} else {
btn.prop('disabled', true);
}
}
$(document).on('change keyup', '.yoone-bundle-qty', updateState);
$(document).ready(updateState);
})(jQuery);
</script>

View File

@ -1,7 +1,7 @@
<?php <?php
/** /**
* Plugin Name: Yoone Product Bundles (混装产品) * Plugin Name: Yoone Product Bundles
* Description: WooCommerce 提供“混装产品Bundle”类型在后台为某个产品配置可混装的简单商品与最小混装数量前端允许顾客按分类选择混装商品与数量当达到最小数量时可加入购物车结算价格为所选商品的价格总和。 * Description: Adds a "Mix and Match" product type to WooCommerce. Allows creating a bundle product where customers can select from a list of simple products, set quantities, and add to cart if a minimum quantity is met. The price is the sum of the selected products.
* Author: Yoone * Author: Yoone
* Version: 0.1.0 * Version: 0.1.0
* Requires at least: 6.0 * Requires at least: 6.0
@ -12,15 +12,15 @@
defined('ABSPATH') || exit; defined('ABSPATH') || exit;
// 简单防御:确保 WooCommerce 已激活 // Basic defense: ensure WooCommerce is active
if (! function_exists('WC')) { if (! function_exists('WC')) {
add_action('admin_notices', function () { add_action('admin_notices', function () {
echo '<div class="notice notice-error"><p>Yoone Product Bundles 需要启用 WooCommerce。</p></div>'; echo '<div class="notice notice-error"><p>' . esc_html__('Yoone Product Bundles requires WooCommerce to be activated.', 'yoone-product-bundles') . '</p></div>';
}); });
return; return;
} }
// 插件常量(路径) // Plugin constants (paths)
define('YOONE_PB_PATH', plugin_dir_path(__FILE__)); define('YOONE_PB_PATH', plugin_dir_path(__FILE__));
define('YOONE_PB_URL', plugin_dir_url(__FILE__)); define('YOONE_PB_URL', plugin_dir_url(__FILE__));
@ -38,10 +38,13 @@ add_action('plugins_loaded', function () {
Yoone_Product_Bundles_Frontend::instance(); Yoone_Product_Bundles_Frontend::instance();
}); });
// 插件版本号
define('YOONE_PB_VERSION', '0.1.1');
// 资源加载(前端样式/脚本) // 资源加载(前端样式/脚本)
add_action('wp_enqueue_scripts', function () { add_action('wp_enqueue_scripts', function () {
wp_register_style('yoone-pb-frontend', YOONE_PB_URL . 'assets/css/frontend.css', array(), '0.1.0'); wp_enqueue_style('yoone-pb-frontend', YOONE_PB_URL . 'assets/css/frontend.css', array(), YOONE_PB_VERSION);
wp_register_script('yoone-pb-frontend', YOONE_PB_URL . 'assets/js/frontend.js', array('jquery'), '0.1.0', true); wp_enqueue_script('yoone-pb-frontend', YOONE_PB_URL . 'assets/js/frontend.js', array('jquery'), YOONE_PB_VERSION, true);
}); });
// 后台资源 // 后台资源
@ -52,7 +55,8 @@ add_action('admin_enqueue_scripts', function ($hook) {
if ($screen && 'product' === $screen->post_type) { if ($screen && 'product' === $screen->post_type) {
wp_enqueue_style('woocommerce_admin_styles'); wp_enqueue_style('woocommerce_admin_styles');
wp_enqueue_script('wc-product-search'); // Woo 的 select2 产品搜索 wp_enqueue_script('wc-product-search'); // Woo 的 select2 产品搜索
wp_enqueue_style('yoone-pb-admin', YOONE_PB_URL . 'assets/css/admin.css', array(), '0.1.0'); wp_enqueue_style('yoone-pb-admin', YOONE_PB_URL . 'assets/css/admin.css', array(), YOONE_PB_VERSION);
wp_enqueue_script('yoone-pb-admin', YOONE_PB_URL . 'assets/js/admin.js', array('jquery'), YOONE_PB_VERSION, true);
} }
} }
}); });