0
0
Wordpressframework~5 mins

Data escaping (output) in Wordpress

Choose your learning style9 modes available
Introduction

Data escaping helps keep your website safe by cleaning output before showing it. It stops bad code from running on your site.

When showing user input on a page to avoid harmful scripts.
When printing data from the database that might contain special characters.
When adding dynamic content inside HTML attributes like links or image tags.
When displaying text that could include HTML or JavaScript from unknown sources.
Syntax
Wordpress
esc_html( $data )
esc_attr( $data )
esc_url( $url )
esc_js( $data )

esc_html() cleans text for safe HTML output.

esc_attr() cleans data for HTML attributes like title or alt.

Examples
Shows user input safely inside HTML content.
Wordpress
echo esc_html( $user_input );
Makes sure the URL is safe before adding it to a link.
Wordpress
echo '<a href="' . esc_url( $link ) . '">Click here</a>';
Escapes data inside an HTML attribute to avoid breaking the tag.
Wordpress
echo '<input type="text" value="' . esc_attr( $value ) . '">';
Sample Program

This example shows how to safely display user input, URLs, and attribute values using WordPress escaping functions. It prevents harmful scripts from running and keeps HTML valid.

Wordpress
<?php
// Simulate user input with special characters
$user_input = '<script>alert("hack")</script> Hello!';
$link = 'javascript:alert(1)';
$value = 'O\'Reilly & Co.';

// Safe output using escaping functions
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Data Escaping Example</title>
</head>
<body>
  <h1>Escaped User Input:</h1>
  <p><?php echo esc_html($user_input); ?></p>

  <h2>Safe Link:</h2>
  <a href="<?php echo esc_url($link); ?>">Click me</a>

  <h2>Input Value:</h2>
  <input type="text" value="<?php echo esc_attr($value); ?>">
</body>
</html>
OutputSuccess
Important Notes

Always escape data right before output, not before storing it.

Use the right escaping function for the context: HTML content, attributes, URLs, or JavaScript.

Escaping helps protect your site from security risks like cross-site scripting (XSS).

Summary

Data escaping cleans output to keep your site safe.

Use esc_html(), esc_attr(), and esc_url() depending on where data goes.

Always escape data when showing it, especially if it comes from users or external sources.