0
0
Wordpressframework~30 mins

XSS prevention in Wordpress - Mini Project: Build & Apply

Choose your learning style9 modes available
XSS Prevention in WordPress Theme
📖 Scenario: You are building a simple WordPress theme that displays user-submitted comments safely.Users can enter comments on posts, but you want to prevent harmful scripts from running on your site.
🎯 Goal: Build a WordPress theme snippet that safely outputs user comments by preventing cross-site scripting (XSS) attacks using WordPress functions.
📋 What You'll Learn
Create a PHP array called $comments with exact user comment strings including one with a script tag
Add a variable $allowed_tags that defines which HTML tags are allowed in comments
Use wp_kses() function to sanitize each comment allowing only the allowed tags
Echo the sanitized comments inside <div> elements in a loop
💡 Why This Matters
🌍 Real World
Preventing XSS attacks is critical when displaying user-generated content on WordPress sites to keep visitors safe.
💼 Career
Web developers must know how to sanitize and escape content properly to build secure WordPress themes and plugins.
Progress0 / 4 steps
1
Create the comments data array
Create a PHP array called $comments with these exact strings: 'Hello, this is safe!', 'Nice post! <script>alert("XSS")</script>', and 'Thanks for sharing.'
Wordpress
Need a hint?

Use square brackets [] to create the array and include the exact strings with quotes.

2
Define allowed HTML tags for comments
Add a variable called $allowed_tags that allows only <b> and <i> tags in comments. Use an associative array with keys 'b' and 'i' and empty arrays as values.
Wordpress
Need a hint?

Allowed tags array keys are tag names as strings, values are empty arrays.

3
Sanitize comments using wp_kses
Use a foreach loop with variable $comment to iterate over $comments. Inside the loop, create a variable $safe_comment that stores the sanitized comment using wp_kses($comment, $allowed_tags).
Wordpress
Need a hint?

Use foreach ($comments as $comment) and assign sanitized result to $safe_comment.

4
Output sanitized comments inside div elements
Inside the foreach loop, echo each $safe_comment wrapped in a <div> element. Use echo '<div>' . $safe_comment . '</div>'; exactly.
Wordpress
Need a hint?

Use string concatenation to wrap the sanitized comment in a div and echo it.