0
0
Wordpressframework~5 mins

XSS prevention in Wordpress

Choose your learning style9 modes available
Introduction

XSS prevention helps keep your website safe by stopping bad code from running in users' browsers.

When displaying user comments on your blog
When showing user profile information
When accepting input from forms and displaying it back
When adding dynamic content from external sources
When creating plugins or themes that handle user data
Syntax
Wordpress
<?php
// Escape output to prevent XSS
echo esc_html( $user_input );
?>

Use esc_html() to safely show text in HTML.

WordPress has many escaping functions for different contexts.

Examples
Escapes comment text before showing it in HTML.
Wordpress
<?php echo esc_html( $comment_text ); ?>
Escapes data used inside HTML attributes.
Wordpress
<?php echo esc_attr( $input_value ); ?>
Allows safe HTML tags in post content but removes harmful ones.
Wordpress
<?php echo wp_kses_post( $post_content ); ?>
Sample Program

This example shows how a script tag in user input is turned into safe text so it does not run as code.

Wordpress
<?php
// Simulate user input with a script tag
$user_input = '<script>alert("XSS")</script>Hello!';

// Safe output using esc_html
$safe_output = esc_html( $user_input );

echo "User says: " . $safe_output;
?>
OutputSuccess
Important Notes

Always escape data when outputting it, never trust user input.

Use the right escaping function for the place where data appears (HTML, attribute, URL, JavaScript).

WordPress provides many helpers like esc_html(), esc_attr(), and wp_kses_post().

Summary

XSS prevention stops harmful scripts from running on your site.

Escape all user data before showing it on pages.

Use WordPress built-in escaping functions for safety.