如何在WooCommerce自定义设置页签中添加WP编辑器(WYSIWYG)
在WooCommerce自定义设置页签中添加WP编辑器(WYSIWYG)字段
WooCommerce默认设置字段类型里没有直接的编辑器选项,要实现这个需要两步:添加字段定义,再通过钩子渲染WP编辑器,同时确保内容能正确保存。
1. 修改设置字段数组
在你的get_settings()函数里,在下拉字段和section_end之间添加一个自定义类型的字段:
public static function get_settings() { $product_categories_slug = ['value1', 'value2']; $settings = array( 'section_title' => array( 'name' => __('VIP settings', 'woocommerce-settings-tab-wc-vip'), 'type' => 'title', 'desc' => '', 'id' => 'wc_settings_tab_wc_vip_section_title' ), 'vip_cat_slug' => array( 'name' => __('VIP category slug', 'woocommerce-settings-tab-wc-vip'), 'type' => 'select', 'options' => $product_categories_slug, 'desc' => __('Select the category used for VIP', 'woocommerce-settings-tab-wc-vip'), 'id' => 'vip_cat_slug' ), // 新增WP编辑器字段 'vip_description' => array( 'name' => __('VIP 描述内容', 'woocommerce-settings-tab-wc-vip'), 'type' => 'wysiwyg', // 自定义类型,供钩子识别 'desc' => __('编辑VIP专属的描述内容', 'woocommerce-settings-tab-wc-vip'), 'id' => 'vip_description', 'css' => 'width: 100%;', // 可选:设置编辑器宽度 ), 'section_end' => array( 'type' => 'sectionend', 'id' => 'wc_settings_tab_wc_vip_section_end' ) ); return apply_filters('wc_settings_tab_wc_vip_settings', $settings); }
2. 添加编辑器渲染钩子
在你的类或插件文件中,添加钩子函数来渲染WP编辑器:
// 渲染自定义WYSIWYG字段 add_action('woocommerce_admin_field_wysiwyg', function($field) { // 获取已保存的设置值 $value = get_option($field['id'], ''); echo '<tr valign="top">'; echo '<th scope="row" class="titledesc">'; echo '<label for="' . esc_attr($field['id']) . '">' . esc_html($field['name']) . '</label>'; echo '</th>'; echo '<td class="forminp forminp-' . esc_attr($field['type']) . '">'; // 渲染WP编辑器 wp_editor( $value, $field['id'], array( 'textarea_name' => $field['id'], 'textarea_rows' => 10, 'media_buttons' => true, // 是否显示媒体上传按钮 'tinymce' => true, // 是否启用可视化编辑器 'quicktags' => true // 是否启用代码快速标签 ) ); if (!empty($field['desc'])) { echo '<p class="description">' . wp_kses_post($field['desc']) . '</p>'; } echo '</td>'; echo '</tr>'; });
3. 确保内容正确保存(可选但推荐)
如果需要过滤保存的内容(比如清理非法HTML标签),可以添加设置保存钩子:
// 过滤并保存编辑器内容 add_filter('woocommerce_settings_save_wc_vip', function($settings) { if (isset($_POST['vip_description'])) { // 使用wp_kses_post保留合法HTML标签 update_option('vip_description', wp_kses_post($_POST['vip_description'])); } return $settings; });
做完以上操作,你的自定义设置页签里就会出现一个完整的WP编辑器,和原有下拉字段一起正常工作。
内容的提问来源于stack exchange,提问作者ArbreMojo
相关产品推荐
相关产品推荐

