如何让WordPress输入框支持HTML标签(含WooCommerce Product Subtitle插件)
Hey there! Let's break down your problem into two clear parts—fixing HTML support for the WooCommerce Product Subtitle plugin, and understanding how to enable HTML in WordPress input boxes generally.
1. Getting HTML to Work in WooCommerce Product Subtitle Plugin
The plugin's input box probably sanitizes your input to strip HTML by default (a standard security measure). Here are two reliable ways to fix this:
Option 1: Use a Filter Hook (Recommended)
Most well-built plugins include filter hooks that let you modify their output without editing core plugin files (which get overwritten on updates). The WooCommerce Product Subtitle plugin likely has a filter for the subtitle content.
Add this code to your child theme's functions.php file (or a custom plugin):
add_filter( 'woocommerce_product_subtitle', 'allow_safe_html_in_product_subtitle', 10, 1 ); function allow_safe_html_in_product_subtitle( $subtitle ) { // wp_kses_post allows common safe HTML tags (p, strong, em, a, etc.) return wp_kses_post( $subtitle ); }
This tells WordPress to render safe HTML tags instead of escaping them. If you need to allow specific extra tags, define a custom allowed list:
add_filter( 'woocommerce_product_subtitle', 'allow_custom_html_in_product_subtitle', 10, 1 ); function allow_custom_html_in_product_subtitle( $subtitle ) { $allowed_tags = array( 'a' => array( 'href' => array(), 'title' => array() ), 'strong' => array(), 'em' => array(), 'br' => array(), 'span' => array( 'class' => array() ) ); return wp_kses( $subtitle, $allowed_tags ); }
Option 2: Modify the Plugin's Output (Not Recommended)
If the plugin doesn't have a filter hook, you could edit the plugin's template file where it outputs the subtitle. Look for a line like:
echo esc_html( $subtitle );
Change it to:
echo wp_kses_post( $subtitle );
Warning: This change will be lost when you update the plugin, so only do this if you can't use the filter method, and remember to reapply it after updates.
2. General Guide to Enable HTML in WordPress Input Boxes
WordPress sanitizes user input by default to prevent security risks like XSS attacks. To enable HTML support safely, follow these rules:
When Saving Data: Instead of using
sanitize_text_field()(which strips all HTML), usewp_kses_post()(for post-like content) orwp_kses()(for custom tag lists) to sanitize input while keeping safe HTML.
Example for saving a custom post meta field:update_post_meta( $post_id, 'my_custom_input', wp_kses_post( $_POST['my_custom_input'] ) );When Outputting Data: Don't use
esc_html()(which escapes HTML) for fields that should render HTML. Instead, useecho wp_kses_post( get_post_meta( get_the_ID(), 'my_custom_input', true ) );to safely render the HTML.Avoid Unsafe Practices: Never directly output raw user input without sanitizing it. Even if you trust your users, unfiltered HTML can lead to security vulnerabilities.
内容的提问来源于stack exchange,提问作者Muhammed Nasser

