文章目录[隐藏]
开发支持小批量个性化刻印的WordPress插件教程
概述
在当今电商环境中,个性化定制产品越来越受欢迎。本教程将指导您开发一个支持小批量个性化刻印的WordPress插件,允许客户在产品上添加自定义文本或图案,适用于纪念品、礼品、办公用品等场景。
插件功能规划
我们的插件将包含以下核心功能:
- 在产品页面添加个性化刻印选项
- 支持文本和简单图案选择
- 实时预览刻印效果
- 小批量订单管理(1-50件)
- 刻印数据存储和导出
开发环境准备
在开始之前,请确保您具备以下环境:
- WordPress 5.0+ 安装
- PHP 7.2+ 环境
- 基础的HTML/CSS/JavaScript知识
- 代码编辑器(如VS Code)
创建插件基础结构
首先,在WordPress的wp-content/plugins/目录下创建插件文件夹personalized-engraving,并创建以下文件结构:
personalized-engraving/
├── personalized-engraving.php # 主插件文件
├── includes/
│ ├── class-engraving-admin.php # 后台管理类
│ ├── class-engraving-frontend.php # 前端显示类
│ └── class-engraving-db.php # 数据库处理类
├── assets/
│ ├── css/
│ │ └── engraving-styles.css # 样式文件
│ └── js/
│ └── engraving-scripts.js # 脚本文件
└── templates/
└── engraving-interface.php # 前端模板
主插件文件开发
打开personalized-engraving.php,添加以下代码:
<?php
/**
* Plugin Name: 个性化刻印系统
* Plugin URI: https://yourwebsite.com/
* Description: 支持小批量个性化刻印的WordPress插件
* Version: 1.0.0
* Author: 您的名字
* License: GPL v2 or later
* Text Domain: personalized-engraving
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
// 定义插件常量
define('PE_PLUGIN_PATH', plugin_dir_path(__FILE__));
define('PE_PLUGIN_URL', plugin_dir_url(__FILE__));
define('PE_VERSION', '1.0.0');
// 检查必要依赖
add_action('admin_init', 'pe_check_woocommerce_dependency');
function pe_check_woocommerce_dependency() {
if (!class_exists('WooCommerce')) {
add_action('admin_notices', function() {
echo '<div class="notice notice-error"><p>';
echo __('个性化刻印插件需要WooCommerce支持,请先安装并激活WooCommerce插件。', 'personalized-engraving');
echo '</p></div>';
});
}
}
// 自动加载类文件
spl_autoload_register('pe_autoloader');
function pe_autoloader($class_name) {
if (strpos($class_name, 'PE_') === 0) {
$file = PE_PLUGIN_PATH . 'includes/class-' . strtolower(str_replace('_', '-', $class_name)) . '.php';
if (file_exists($file)) {
require_once $file;
}
}
}
// 初始化插件
add_action('plugins_loaded', 'pe_init_plugin');
function pe_init_plugin() {
// 只有WooCommerce存在时才加载插件功能
if (class_exists('WooCommerce')) {
// 实例化主类
$GLOBALS['personalized_engraving'] = new PE_Main();
}
}
// 主类
class PE_Main {
public function __construct() {
$this->init_hooks();
}
private function init_hooks() {
// 加载文本域
add_action('init', array($this, 'load_textdomain'));
// 注册激活/停用钩子
register_activation_hook(__FILE__, array('PE_DB', 'create_tables'));
register_deactivation_hook(__FILE__, array($this, 'deactivate'));
// 根据上下文加载前端或后台
if (is_admin()) {
new PE_Admin();
} else {
new PE_Frontend();
}
}
public function load_textdomain() {
load_plugin_textdomain('personalized-engraving', false, dirname(plugin_basename(__FILE__)) . '/languages/');
}
public function deactivate() {
// 清理临时数据
// 注意:这里不删除数据库表,以便保留数据
flush_rewrite_rules();
}
}
数据库处理类
创建includes/class-engraving-db.php:
<?php
/**
* 数据库处理类
*/
class PE_DB {
/**
* 创建插件需要的数据库表
*/
public static function create_tables() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . 'personalized_engravings';
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
order_id bigint(20) NOT NULL,
product_id bigint(20) NOT NULL,
engraving_text text NOT NULL,
engraving_type varchar(50) NOT NULL DEFAULT 'text',
font_style varchar(100) DEFAULT 'Arial',
font_size int DEFAULT 12,
engraving_position varchar(100) DEFAULT 'center',
quantity int DEFAULT 1,
created_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY order_id (order_id),
KEY product_id (product_id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
// 添加版本选项以便未来更新
add_option('pe_db_version', '1.0');
}
/**
* 保存刻印数据
*/
public static function save_engraving($data) {
global $wpdb;
$table_name = $wpdb->prefix . 'personalized_engravings';
$wpdb->insert(
$table_name,
array(
'order_id' => $data['order_id'],
'product_id' => $data['product_id'],
'engraving_text' => sanitize_text_field($data['engraving_text']),
'engraving_type' => sanitize_text_field($data['engraving_type']),
'font_style' => sanitize_text_field($data['font_style']),
'font_size' => intval($data['font_size']),
'engraving_position' => sanitize_text_field($data['engraving_position']),
'quantity' => intval($data['quantity'])
),
array('%d', '%d', '%s', '%s', '%s', '%d', '%s', '%d')
);
return $wpdb->insert_id;
}
/**
* 获取订单的刻印数据
*/
public static function get_engravings_by_order($order_id) {
global $wpdb;
$table_name = $wpdb->prefix . 'personalized_engravings';
return $wpdb->get_results(
$wpdb->prepare(
"SELECT * FROM $table_name WHERE order_id = %d",
$order_id
)
);
}
}
前端显示类
创建includes/class-engraving-frontend.php:
<?php
/**
* 前端显示类
*/
class PE_Frontend {
public function __construct() {
// 在产品页面添加刻印选项
add_action('woocommerce_before_add_to_cart_button', array($this, 'add_engraving_fields'));
// 验证并保存刻印数据到购物车
add_filter('woocommerce_add_cart_item_data', array($this, 'save_engraving_to_cart'), 10, 2);
// 在购物车中显示刻印信息
add_filter('woocommerce_get_item_data', array($this, 'display_engraving_in_cart'), 10, 2);
// 加载前端资源
add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
}
/**
* 在产品页面添加刻印选项
*/
public function add_engraving_fields() {
global $product;
// 只对支持刻印的产品显示选项
$engraving_enabled = get_post_meta($product->get_id(), '_enable_engraving', true);
if ($engraving_enabled === 'yes') {
include(PE_PLUGIN_PATH . 'templates/engraving-interface.php');
}
}
/**
* 保存刻印数据到购物车
*/
public function save_engraving_to_cart($cart_item_data, $product_id) {
if (isset($_POST['engraving_text']) && !empty($_POST['engraving_text'])) {
$cart_item_data['engraving'] = array(
'text' => sanitize_text_field($_POST['engraving_text']),
'type' => isset($_POST['engraving_type']) ? sanitize_text_field($_POST['engraving_type']) : 'text',
'font_style' => isset($_POST['font_style']) ? sanitize_text_field($_POST['font_style']) : 'Arial',
'font_size' => isset($_POST['font_size']) ? intval($_POST['font_size']) : 12,
'position' => isset($_POST['engraving_position']) ? sanitize_text_field($_POST['engraving_position']) : 'center',
'quantity' => isset($_POST['engraving_quantity']) ? intval($_POST['engraving_quantity']) : 1
);
// 为每个刻印项目生成唯一ID
$cart_item_data['unique_key'] = md5(microtime().rand());
}
return $cart_item_data;
}
/**
* 在购物车中显示刻印信息
*/
public function display_engraving_in_cart($item_data, $cart_item) {
if (isset($cart_item['engraving'])) {
$engraving = $cart_item['engraving'];
$item_data[] = array(
'name' => __('刻印文字', 'personalized-engraving'),
'value' => $engraving['text']
);
$item_data[] = array(
'name' => __('刻印数量', 'personalized-engraving'),
'value' => $engraving['quantity']
);
if ($engraving['type'] !== 'text') {
$item_data[] = array(
'name' => __('刻印类型', 'personalized-engraving'),
'value' => $engraving['type']
);
}
}
return $item_data;
}
/**
* 加载前端脚本和样式
*/
public function enqueue_scripts() {
if (is_product()) {
wp_enqueue_style(
'pe-frontend-style',
PE_PLUGIN_URL . 'assets/css/engraving-styles.css',
array(),
PE_VERSION
);
wp_enqueue_script(
'pe-frontend-script',
PE_PLUGIN_URL . 'assets/js/engraving-scripts.js',
array('jquery'),
PE_VERSION,
true
);
// 本地化脚本,传递数据到JavaScript
wp_localize_script('pe-frontend-script', 'pe_ajax', array(
'ajax_url' => admin_url('admin-ajax.php'),
'preview_nonce' => wp_create_nonce('engraving_preview_nonce')
));
}
}
}
前端模板文件
创建templates/engraving-interface.php:
<div class="personalized-engraving-container">
<h3><?php _e('个性化刻印选项', 'personalized-engraving'); ?></h3>
<div class="engraving-options">
<!-- 刻印类型选择 -->
<div class="engraving-type">
<label for="engraving_type"><?php _e('刻印类型:', 'personalized-engraving'); ?></label>
<select id="engraving_type" name="engraving_type">
<option value="text"><?php _e('文字刻印', 'personalized-engraving'); ?></option>
<option value="monogram"><?php _e('字母组合', 'personalized-engraving'); ?></option>
<option value="symbol"><?php _e('符号/图案', 'personalized-engraving'); ?></option>
</select>
</div>
<!-- 刻印文字输入 -->
<div class="engraving-text">
<label for="engraving_text"><?php _e('刻印文字:', 'personalized-engraving'); ?></label>
<input type="text"
id="engraving_text"
name="engraving_text"
maxlength="50"
placeholder="<?php _e('请输入刻印内容(最多50字符)', 'personalized-engraving'); ?>">
<span class="char-count">0/50</span>
</div>
<!-- 字体样式选择 -->
<div class="font-options">
<label for="font_style"><?php _e('字体:', 'personalized-engraving'); ?></label>
<select id="font_style" name="font_style">
<option value="Arial">Arial</option>
<option value="Times New Roman">Times New Roman</option>
<option value="Courier New">Courier New</option>
<option value="Script"><?php _e('手写体', 'personalized-engraving'); ?></option>
</select>
<label for="font_size"><?php _e('字号:', 'personalized-engraving'); ?></label>
<select id="font_size" name="font_size">
<option value="10">10pt</option>
<option value="12" selected>12pt</option>
<option value="14">14pt</option>
<option value="16">16pt</option>
<option value="18">18pt</option>
</select>
</div>
<!-- 刻印位置选择 -->
<div class="position-options">
<label for="engraving_position"><?php _e('刻印位置:', 'personalized-engraving'); ?></label>
<select id="engraving_position" name="engraving_position">
<option value="center"><?php _e('居中', 'personalized-engraving'); ?></option>
<option value="top"><?php _e('顶部', 'personalized-engraving'); ?></option>
<option value="bottom"><?php _e('底部', 'personalized-engraving'); ?></option>
<option value="left"><?php _e('左侧', 'personalized-engraving'); ?></option>
<option value="right"><?php _e('右侧', 'personalized-engraving'); ?></option>
</select>
</div>
<!-- 刻印数量(小批量支持) -->
<div class="quantity-options">
<label for="engraving_quantity"><?php _e('刻印数量 (1-50):', 'personalized-engraving'); ?></label>
<input type="number"
id="engraving_quantity"
name="engraving_quantity"
min="1"
max="50"
value="1">
<small><?php _e('* 小批量刻印,最多50件', 'personalized-engraving'); ?></small>
</div>
<!-- 实时预览区域 -->
<div class="preview-section">
<h4><?php _e('刻印预览:', 'personalized-engraving'); ?></h4>
<div class="preview-container">
<div class="product-preview">
<!-- 产品基础图像 -->
<?php
$product_image = wp_get_attachment_image_src(get_post_thumbnail_id(get_the_ID()), 'medium');
if ($product_image) {
echo '<img src="' . esc_url($product_image[0]) . '" alt="' . get_the_title() . '" class="base-product">';
}
?>
<!-- 刻印预览层 -->
<div class="engraving-preview"></div>
</div>
<div class="preview-text"></div>
</div>
</div>
<!-- 价格说明 -->
<div class="price-notice">
<p><?php _e('* 个性化刻印可能会产生额外费用,具体费用将在结算时显示。', 'personalized-engraving'); ?></p>
</div>
</div>
</div>
后台管理类
创建includes/class-engraving-admin.php:
<?php
/**
* 后台管理类
*/
class PE_Admin {
public function __construct() {
// 添加产品刻印选项
add_action('woocommerce_product_options_general_product_data', array($this, 'add_product_engraving_option'));
add_action('woocommerce_process_product_meta', array($this, 'save_product_engraving_option'));
// 添加管理菜单
add_action('admin_menu', array($this, 'add_admin_menu'));
// 加载后台资源
add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
}
后台管理类(续)
/**
* 在产品编辑页面添加刻印选项
*/
public function add_product_engraving_option() {
echo '<div class="options_group">';
// 启用刻印选项
woocommerce_wp_checkbox(array(
'id' => '_enable_engraving',
'label' => __('启用个性化刻印', 'personalized-engraving'),
'description' => __('允许客户为此产品添加个性化刻印', 'personalized-engraving'),
'desc_tip' => true,
));
// 刻印额外费用
woocommerce_wp_text_input(array(
'id' => '_engraving_fee',
'label' => __('刻印额外费用', 'personalized-engraving'),
'description' => __('每件产品的刻印额外费用', 'personalized-engraving'),
'desc_tip' => true,
'type' => 'number',
'custom_attributes' => array(
'step' => '0.01',
'min' => '0'
)
));
// 最大字符限制
woocommerce_wp_text_input(array(
'id' => '_max_engraving_chars',
'label' => __('最大字符数', 'personalized-engraving'),
'description' => __('刻印文字的最大允许字符数', 'personalized-engraving'),
'desc_tip' => true,
'type' => 'number',
'default' => '50'
));
echo '</div>';
}
/**
* 保存产品刻印选项
*/
public function save_product_engraving_option($post_id) {
$enable_engraving = isset($_POST['_enable_engraving']) ? 'yes' : 'no';
update_post_meta($post_id, '_enable_engraving', $enable_engraving);
if (isset($_POST['_engraving_fee'])) {
update_post_meta($post_id, '_engraving_fee', sanitize_text_field($_POST['_engraving_fee']));
}
if (isset($_POST['_max_engraving_chars'])) {
update_post_meta($post_id, '_max_engraving_chars', intval($_POST['_max_engraving_chars']));
}
}
/**
* 添加管理菜单
*/
public function add_admin_menu() {
add_submenu_page(
'woocommerce',
__('个性化刻印订单', 'personalized-engraving'),
__('刻印订单', 'personalized-engraving'),
'manage_woocommerce',
'personalized-engravings',
array($this, 'display_engravings_page')
);
}
/**
* 显示刻印订单管理页面
*/
public function display_engravings_page() {
?>
<div class="wrap">
<h1><?php _e('个性化刻印订单管理', 'personalized-engraving'); ?></h1>
<?php
// 处理批量操作
if (isset($_GET['action']) && isset($_GET['engraving_id'])) {
$this->handle_engraving_actions();
}
// 显示刻印订单列表
$this->display_engravings_table();
?>
</div>
<?php
}
/**
* 处理刻印订单操作
*/
private function handle_engraving_actions() {
$action = sanitize_text_field($_GET['action']);
$engraving_id = intval($_GET['engraving_id']);
switch ($action) {
case 'mark_completed':
$this->mark_engraving_completed($engraving_id);
break;
case 'delete':
$this->delete_engraving($engraving_id);
break;
case 'export':
$this->export_engraving_data($engraving_id);
break;
}
}
/**
* 标记刻印为已完成
*/
private function mark_engraving_completed($engraving_id) {
global $wpdb;
$table_name = $wpdb->prefix . 'personalized_engravings';
$wpdb->update(
$table_name,
array('status' => 'completed'),
array('id' => $engraving_id),
array('%s'),
array('%d')
);
echo '<div class="notice notice-success"><p>' .
__('刻印订单已标记为完成。', 'personalized-engraving') .
'</p></div>';
}
/**
* 显示刻印订单表格
*/
private function display_engravings_table() {
global $wpdb;
$table_name = $wpdb->prefix . 'personalized_engravings';
// 获取刻印订单数据
$engravings = $wpdb->get_results(
"SELECT e.*, o.post_title as order_title, p.post_title as product_title
FROM $table_name e
LEFT JOIN {$wpdb->posts} o ON e.order_id = o.ID
LEFT JOIN {$wpdb->posts} p ON e.product_id = p.ID
ORDER BY e.created_at DESC"
);
?>
<table class="wp-list-table widefat fixed striped">
<thead>
<tr>
<th><?php _e('ID', 'personalized-engraving'); ?></th>
<th><?php _e('订单号', 'personalized-engraving'); ?></th>
<th><?php _e('产品', 'personalized-engraving'); ?></th>
<th><?php _e('刻印内容', 'personalized-engraving'); ?></th>
<th><?php _e('数量', 'personalized-engraving'); ?></th>
<th><?php _e('创建时间', 'personalized-engraving'); ?></th>
<th><?php _e('操作', 'personalized-engraving'); ?></th>
</tr>
</thead>
<tbody>
<?php if (empty($engravings)): ?>
<tr>
<td colspan="7"><?php _e('暂无刻印订单', 'personalized-engraving'); ?></td>
</tr>
<?php else: ?>
<?php foreach ($engravings as $engraving): ?>
<tr>
<td><?php echo $engraving->id; ?></td>
<td>
<a href="<?php echo admin_url('post.php?post=' . $engraving->order_id . '&action=edit'); ?>">
#<?php echo $engraving->order_id; ?>
</a>
</td>
<td><?php echo esc_html($engraving->product_title); ?></td>
<td>
<strong><?php echo esc_html($engraving->engraving_text); ?></strong><br>
<small>
<?php echo sprintf(
__('字体: %s, 大小: %dpt', 'personalized-engraving'),
$engraving->font_style,
$engraving->font_size
); ?>
</small>
</td>
<td><?php echo $engraving->quantity; ?></td>
<td><?php echo date_i18n(get_option('date_format'), strtotime($engraving->created_at)); ?></td>
<td>
<a href="<?php echo admin_url('admin.php?page=personalized-engravings&action=mark_completed&engraving_id=' . $engraving->id); ?>"
class="button button-small">
<?php _e('标记完成', 'personalized-engraving'); ?>
</a>
<a href="<?php echo admin_url('admin.php?page=personalized-engraving-export&engraving_id=' . $engraving->id); ?>"
class="button button-small">
<?php _e('导出', 'personalized-engraving'); ?>
</a>
</td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
<div class="tablenav bottom">
<div class="alignleft actions">
<button type="button" class="button" onclick="exportAllEngravings()">
<?php _e('导出所有刻印数据', 'personalized-engraving'); ?>
</button>
</div>
</div>
<script>
function exportAllEngravings() {
if (confirm('<?php _e('确定要导出所有刻印数据吗?', 'personalized-engraving'); ?>')) {
window.location.href = '<?php echo admin_url('admin-ajax.php?action=export_all_engravings'); ?>';
}
}
</script>
<?php
}
/**
* 加载后台脚本和样式
*/
public function enqueue_admin_scripts($hook) {
if ($hook === 'woocommerce_page_personalized-engravings' || $hook === 'post.php') {
wp_enqueue_style(
'pe-admin-style',
PE_PLUGIN_URL . 'assets/css/admin-styles.css',
array(),
PE_VERSION
);
wp_enqueue_script(
'pe-admin-script',
PE_PLUGIN_URL . 'assets/js/admin-scripts.js',
array('jquery'),
PE_VERSION,
true
);
}
}
}
前端样式文件
创建assets/css/engraving-styles.css:
/* 个性化刻印插件前端样式 */
.personalized-engraving-container {
margin: 20px 0;
padding: 20px;
border: 1px solid #ddd;
border-radius: 5px;
background-color: #f9f9f9;
}
.personalized-engraving-container h3 {
margin-top: 0;
color: #333;
border-bottom: 2px solid #0073aa;
padding-bottom: 10px;
}
.engraving-options > div {
margin-bottom: 15px;
}
.engraving-options label {
display: inline-block;
width: 120px;
font-weight: bold;
margin-right: 10px;
}
.engraving-text input {
width: 300px;
padding: 8px;
border: 1px solid #ccc;
border-radius: 3px;
}
.char-count {
margin-left: 10px;
color: #666;
font-size: 12px;
}
.preview-section {
margin-top: 30px;
padding: 15px;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 3px;
}
.preview-container {
display: flex;
gap: 20px;
margin-top: 15px;
}
.product-preview {
position: relative;
width: 300px;
height: 200px;
border: 1px solid #eee;
background-color: #f5f5f5;
}
.base-product {
width: 100%;
height: 100%;
object-fit: contain;
}
.engraving-preview {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
}
.preview-text {
flex: 1;
padding: 15px;
background-color: #f8f8f8;
border-radius: 3px;
font-family: monospace;
white-space: pre-wrap;
}
.quantity-options input {
width: 80px;
padding: 5px;
border: 1px solid #ccc;
border-radius: 3px;
}
.quantity-options small {
margin-left: 10px;
color: #666;
}
.price-notice {
margin-top: 20px;
padding: 10px;
background-color: #fff8e1;
border-left: 4px solid #ffb900;
font-size: 14px;
}
/* 响应式设计 */
@media (max-width: 768px) {
.preview-container {
flex-direction: column;
}
.product-preview {
width: 100%;
height: 150px;
}
.engraving-text input {
width: 100%;
}
}
前端JavaScript文件
创建assets/js/engraving-scripts.js:
/**
* 个性化刻印插件前端脚本
*/
jQuery(document).ready(function($) {
// 字符计数器
$('#engraving_text').on('input', function() {
const maxChars = 50;
const currentChars = $(this).val().length;
const charCount = $('.char-count');
charCount.text(currentChars + '/' + maxChars);
// 超过限制时改变颜色
if (currentChars > maxChars) {
charCount.css('color', 'red');
$(this).val($(this).val().substring(0, maxChars));
} else if (currentChars > maxChars * 0.8) {
charCount.css('color', 'orange');
} else {
charCount.css('color', '#666');
}
// 更新预览
updatePreview();
});
// 更新刻印预览
function updatePreview() {
const engravingText = $('#engraving_text').val();
const fontStyle = $('#font_style').val();
const fontSize = $('#font_size').val() + 'pt';
const position = $('#engraving_position').val();
// 更新文本预览
$('.preview-text').text(engravingText || '刻印预览将在此显示');
// 更新视觉预览
const preview = $('.engraving-preview');
preview.empty();
if (engravingText) {
const textSpan = $('<span>').text(engravingText)
.css({
'position': 'absolute',
'font-family': fontStyle,
'font-size': fontSize,
'color': '#333',
'font-weight': 'bold',
'text-shadow': '1px 1px 2px rgba(0,0,0,0.3)'
});
// 根据位置设置样式
switch(position) {
case 'center':
textSpan.css({
'top': '50%',
'left': '50%',
'transform': 'translate(-50%, -50%)'
});
break;
case 'top':
textSpan.css({
'top': '20px',
'left': '50%',
'transform': 'translateX(-50%)'
});
break;
case 'bottom':
textSpan.css({
'bottom': '20px',
'left': '50%',
'transform': 'translateX(-50%)'
});
break;
case 'left':
textSpan.css({
'top': '50%',
'left': '20px',
'transform': 'translateY(-50%)'
});
break;
case 'right':
textSpan.css({
'top': '50%',
'right': '20px',
'transform': 'translateY(-50%)'
});
break;
}
preview.append(textSpan);
}
}
// 监听所有相关字段的变化
$('#engraving_type, #font_style, #font_size, #engraving_position').on('change', updatePreview);
// 初始化预览
updatePreview();
// 表单验证
$('form.cart').on('submit', function(e) {
const engravingText = $('#engraving_text').val();
const engravingEnabled = $('.personalized-engraving-container').length > 0;
if (engravingEnabled && (!engravingText || engravingText.trim() === '')) {
e.preventDefault();
alert('请填写刻印内容或移除刻印选项。');
$('#engraving_text').focus();
return false;
}
const quantity = parseInt($('#engraving_quantity').val());
if (quantity < 1 || quantity > 50) {
e.preventDefault();
alert('刻印数量必须在1-50之间。');
$('#engraving_quantity').focus();
return false;
}
});
// 小批量数量验证
$('#engraving_quantity').on('change', function() {
let value = parseInt($(this).val());
if (isNaN(value) || value < 1) {
$(this).val(1);
} else if (value > 50) {
$(this).val(50);
}
});
});
订单处理和价格计算
在includes/class-engraving-frontend.php中添加以下方法:
/**
* 计算刻印额外费用
*/
public function calculate_engraving_fee($cart_object) {
foreach ($cart_object->cart_contents as $key => $value) {
if (isset($value['engraving'])) {
$product_id = $value['product_id'];
$engraving_fee = get_post_meta($product_id, '_engraving_fee', true);
$quantity = $value['engraving']['quantity'];
if ($engraving_fee && is_numeric($engraving_fee)) {
$extra_fee = floatval($engraving_fee) * $quantity;
// 添加额外费用
$value['data']->set_price($value['data']->get_price() + $extra_fee);
// 在购物车项目中存储费用信息
$value['engraving_fee'] = $extra_fee;
$cart_object->cart_contents[$key] = $value;
}
}
}
}
/**
* 在订单中保存刻印数据
*/
