为WooCommerce产品自定义标签添加WYSIWYG编辑器
替换WooCommerce产品自定义字段为WYSIWYG编辑器,解决代码片段显示问题
我来帮你搞定这个问题——你当前的代码用了普通文本输入框,再加上保存时用了esc_html()转义所有HTML内容,导致Visual Composer这类短码/HTML代码直接以纯文本形式显示在前端。换成WordPress原生的WYSIWYG(所见即所得)编辑器就能解决这个问题,同时还能让后台编辑更直观。
关键修改点:
- 把
woocommerce_wp_textarea_input()替换为wp_editor(),这是WordPress自带的可视化编辑器函数 - 调整保存逻辑:用
wp_kses_post()替代esc_html(),既保留合法的HTML和短码,又能过滤恶意代码 - 清理重复的字段添加钩子(你原来的代码里有两个重复的
add_action,会导致后台显示两个相同的字段) - 前端输出时直接渲染编辑器生成的内容,不需要额外转义
修改后的完整代码:
// 添加WYSIWYG编辑器字段到产品后台 add_action( 'woocommerce_product_options_general_product_data', 'wp_amaoni_de_add_custom_product_field' ); function wp_amaoni_de_add_custom_product_field() { global $post; // 获取已保存的内容 $tab_content = get_post_meta( $post->ID, '_custom_tab_description', true ); // 渲染WYSIWYG编辑器 wp_editor( $tab_content, '_custom_tab_description', array( 'textarea_name' => '_custom_tab_description', 'media_buttons' => false, // 可选:是否显示媒体上传按钮,按需开启 'textarea_rows' => 10, 'tinymce' => array( 'toolbar1' => 'bold,italic,underline,link,unlink,undo,redo,formatselect', // 自定义工具栏按钮 'toolbar2' => '', // 关闭第二行工具栏 ), 'quicktags' => true, // 保留文本模式的快速标签 ) ); // 添加字段说明 echo '<p class="description">' . __( '在这里输入自定义标签内容,支持HTML和Visual Composer短码' ) . '</p>'; } // 保存自定义字段内容 add_action( 'woocommerce_process_product_meta', 'wp_amaoni_de_save_custom_product_field' ); function wp_amaoni_de_save_custom_product_field( $post_id ){ // 检查权限并处理内容 if ( current_user_can( 'edit_post', $post_id ) && isset( $_POST['_custom_tab_description'] ) ) { // 安全处理内容:保留合法HTML和短码,过滤恶意代码 $clean_content = wp_kses_post( wp_unslash( $_POST['_custom_tab_description'] ) ); update_post_meta( $post_id, '_custom_tab_description', $clean_content ); } else { // 如果内容为空,删除元数据 delete_post_meta( $post_id, '_custom_tab_description' ); } } // 添加自定义产品标签 add_filter( 'woocommerce_product_tabs', 'wp_amaoni_de_add_woocommerce_product_tabs' ); function wp_amaoni_de_add_woocommerce_product_tabs( $tabs ) { $tabs['wp_amaoni_de_custom_tab'] = array( 'title' => __( 'New Product Tab' ), 'priority' => 50, 'callback' => 'wp_amaoni_de_new_product_tab_callback' ); return $tabs; } // 渲染自定义标签内容 function wp_amaoni_de_new_product_tab_callback() { global $post; $tab_content = get_post_meta( $post->ID, '_custom_tab_description', true ); // 直接输出处理好的内容,不需要额外转义 echo $tab_content; }
额外说明:
- 我删掉了你原来代码中重复的
wp_bibel_de_add_custom_product_field函数和对应的钩子,避免后台出现两个相同的字段 - 编辑器的工具栏可以通过
tinymce参数自定义,你可以根据需求添加或移除按钮 wp_kses_post()是WordPress推荐的安全处理前端显示内容的函数,它会保留所有允许的HTML标签和属性,同时过滤掉危险代码,比直接保存未处理的内容更安全
内容的提问来源于stack exchange,提问作者limilo
相关产品推荐
相关产品推荐

