如何手动在Product Cat分类法中添加并编辑wp_editor字段
为WooCommerce产品分类(Product Cat)添加带TinyMCE编辑器的自定义字段
问题分析
你之前的编辑页面代码无法正常显示已有内容,核心原因是:
wp_editor()的第一个参数就是编辑器要加载的内容,不存在value这个配置项- 编辑分类时,要获取的是分类元数据,而非文章元数据(你之前误用了
get_post_meta())
完整实现代码
以下是正确的手动实现代码,包含新增分类页面、编辑分类页面的字段渲染,以及数据保存逻辑:
1. 新增分类页面添加编辑器字段
add_action( 'product_cat_add_form_fields', 'cxc_add_product_cat_editor_field', 10 ); function cxc_add_product_cat_editor_field() { ?> <div class="form-field"> <label for="cat_custom_content"><?php _e( '分类自定义内容', 'cxc-codexcoach' ); ?></label> <?php wp_editor( '', // 新增分类时内容为空 'cat_custom_content', array( 'wpautop' => true, 'media_buttons' => true, 'textarea_name' => 'cat_custom_content', 'textarea_rows' => 8, 'editor_class' => 'product-cat-editor', 'tinymce' => true, 'quicktags' => true, ) ); ?> <p class="description"><?php _e( '输入分类的自定义富文本内容', 'cxc-codexcoach' ); ?></p> </div> <?php }
2. 编辑分类页面加载已有内容
add_action( 'product_cat_edit_form_fields', 'cxc_edit_product_cat_editor_field', 10, 2 ); function cxc_edit_product_cat_editor_field( $term ) { $term_id = $term->term_id; // 获取已保存的分类元数据 $cat_content = get_term_meta( $term_id, 'cat_custom_content', true ); ?> <tr class="form-field"> <th scope="row" valign="top"> <label for="cat_custom_content"><?php _e( '分类自定义内容', 'cxc-codexcoach' ); ?></label> </th> <td> <?php wp_editor( $cat_content, // 直接传入已保存的内容作为编辑器初始值 'cat_custom_content', array( 'wpautop' => true, 'media_buttons' => true, 'textarea_name' => 'cat_custom_content', 'textarea_rows' => 8, 'editor_class' => 'product-cat-editor', 'tinymce' => true, 'quicktags' => true, ) ); ?> <p class="description"><?php _e( '修改分类的自定义富文本内容', 'cxc-codexcoach' ); ?></p> </td> </tr> <?php }
3. 保存分类编辑器内容
add_action( 'edited_product_cat', 'cxc_save_product_cat_editor_meta', 10, 2 ); add_action( 'create_product_cat', 'cxc_save_product_cat_editor_meta', 10, 2 ); function cxc_save_product_cat_editor_meta( $term_id ) { if ( isset( $_POST['cat_custom_content'] ) ) { // 用wp_kses_post过滤内容,保留合法HTML标签同时保障安全 update_term_meta( $term_id, 'cat_custom_content', wp_kses_post( $_POST['cat_custom_content'] ) ); } }
关键说明
- 编辑器的
textarea_name必须和保存时获取的$_POST键名完全一致 - 编辑页面中,直接将
get_term_meta()获取的已有内容传入wp_editor()的第一个参数,即可正常加载历史内容 - 使用
wp_kses_post()过滤保存的内容,既保留编辑器生成的合法HTML标签,又能防止恶意代码注入
内容的提问来源于stack exchange,提问作者libertarian
相关产品推荐
相关产品推荐

