Exciting News! Flipper Code is now WePlugins! Same commitment to excellence, brand new identity.

How to use esc_html filter in WordPress

Sandeep Kumar Mishra
Sandeep Kumar Mishra
June 21, 2023
5 minutes read

You’ve got a WordPress site and you’re diving into hooks, right? Well, you’re in the right place! Here, we’re going to talk about the esc_html filter. This nifty filter cleans up text by stripping away those pesky invalid or special characters before outputting them. Let’s break it down with some live examples and a bit of friendly guidance.

Example 1: Basic Filter Usage

First things first, to use the esc_html filter, you’ve got to register it with add_filter. Here’s a simple example you can throw into your theme’s functions.php or even better, a custom plugin!

    function weplugins_modify_esc_html_defaults($safe_text, $text) { 
        // Update the $safe_text variable according to your website requirements 
        return $safe_text; 
    }
    // add the filter
    add_filter( "esc_html", "weplugins_modify_esc_html_defaults", 10, 2 );
    

Example 2: Removing a Hook

Sometimes, you may want to remove a hook after it’s served its purpose. For that, remove_filter comes to the rescue.

    remove_filter( "esc_html", "weplugins_modify_esc_html_defaults", 10, 2 );
    

Remember, you need to provide the same callback function name, priority, and number of arguments when removing the hook.

Example 3: Customizing Safe Text

Here’s a more customized example where you might want to modify the $safe_text conditionally based on your site’s needs.

    function weplugins_custom_esc_html($safe_text, $text) { 
        if (condition_to_check) {
            // Modify $safe_text
        }
        return $safe_text; 
    }
    add_filter( "esc_html", "weplugins_custom_esc_html", 10, 2 );
    

Below are the two parameters required to use this hook:

  • $safe_text: (string) The text after it has been escaped.
  • $text: (string) The text prior to being escaped.

Access Premium WordPress Plugins

Contact Us for Customization

If you need any customization or run into issues, don’t hesitate to contact us. We’re here to help make your WordPress experience smoother!

Sandeep Kumar Mishra

Sandeep Kumar Mishra

Sandeep Kumar Mishra writes about WordPress and Artificial Intelligence, offering tips and guides to help you master your website and stay updated with the latest tech trends.

Explore the latest in WordPress

Trying to stay on top of it all? Get the best tools, resources and inspiration sent to your inbox every Wednesday.