WordPress自定义meta box集成editTable.js实现WooCommerce尺码表数据保存
WooCommerce 产品独立尺码表数据保存实现方案
1. 修改Meta Box渲染逻辑
调整render_metabox方法,新增隐藏表单字段存储序列化的表格数据,同时读取已保存的尺码表数据回传给前端,用于编辑时回显:
// Render the meta box public function render_metabox( $post ) { wp_nonce_field( 'custom_nonce_action', 'custom_nonce' ); // 读取已保存的尺码表数据 $size_data = get_post_meta( $post->ID, 'product_size_guide', true ); // 输出隐藏字段存表格JSON数据 echo '<input type="hidden" id="size_guide_data" name="size_guide_data" value="' . esc_attr( $size_data ) . '">'; echo '<div id="edittable"></div>'; }
2. 调整前端JS初始化逻辑
修改editTable初始化代码,实现两个功能:编辑页加载时如果有已存数据就用该数据初始化表格;监听产品表单提交事件,将表格数据序列化后写入隐藏字段:
jQuery(document).ready(function(){ // 读取已存的JSON数据 var savedData = jQuery('#size_guide_data').val(); var initData = savedData ? JSON.parse(savedData) : [['']]; var mytable = jQuery('#edittable').editTable({ data: initData, // 替换默认的空数据 tableClass: 'inputtable', jsonData: false, headerCols: false, maxRows: 999, first_row: true, row_template: false, field_templates: false, validate_field: function (col_id, value, col_type, $element) { return true; } }); // 监听产品表单提交事件 jQuery('form#post').on('submit', function(){ // 获取当前表格数据 转成JSON写入隐藏字段 var tableData = mytable.getData(); jQuery('#size_guide_data').val(JSON.stringify(tableData)); }); });
3. 完善后台保存逻辑
在save_metabox方法中新增数据接收、校验、存储逻辑:
public function save_metabox( $post_id, $post ) { $nonce_name = isset( $_POST['custom_nonce'] ) ? $_POST['custom_nonce'] : ''; $nonce_action = 'custom_nonce_action'; if ( ! wp_verify_nonce( $nonce_name, $nonce_action ) ) { return; } if ( ! current_user_can( 'edit_post', $post_id ) ) { return; } if ( wp_is_post_autosave( $post_id ) ) { return; } if ( wp_is_post_revision( $post_id ) ) { return; } // 新增保存逻辑 if ( isset( $_POST['size_guide_data'] ) ) { // 清理输入的JSON数据 $safe_data = sanitize_text_field( $_POST['size_guide_data'] ); // 存入自定义字段 update_post_meta( $post_id, 'product_size_guide', $safe_data ); } }
注意事项
- 原资源加载逻辑仅适配了已有产品的编辑页,新增产品页不会加载editTable资源,可修改
wpdocs_selectively_enqueue_admin_script的判断逻辑:
function wpdocs_selectively_enqueue_admin_script($hook) { if ( ! in_array( $hook, array( 'post.php', 'post-new.php' ) ) ) { return; } $screen = get_current_screen(); if ( $screen->post_type !== 'product' ) { return; } wp_enqueue_script( 'edittable-js', get_template_directory_uri() . '/inc/editTable/jquery.edittable.min.js', array('jquery'), '1.0' ); wp_enqueue_style( 'edittable-css', get_template_directory_uri() . '/inc/editTable/jquery.edittable.min.css', array(), '1.0' ); }
- 前端产品页展示尺码表时,直接调用
get_post_meta( get_the_ID(), 'product_size_guide', true )获取JSON数据,json_decode后遍历生成HTML表格即可。
内容的提问来源于stack exchange,提问作者dominotrix
相关产品推荐
相关产品推荐

