Home • Blog • Article

How to Recover Your Hacked WordPress Website: A Step-by-Step Guide

By Fathima Nourin TM • •
, ,

WordPress Compromise Incident Response: Threat Analysis and Recovery Architecture

A WordPress site compromise exposes underlying vulnerabilities in the application layer, server configuration, or third-party extension ecosystem. When malicious actors successfully inject payloads into a WordPress instance, they typically establish persistence via administrative backdoors, file injections, database alterations, and .htaccess manipulations. Left unaddressed, these exploits lead to search engine blacklisting, data exfiltration, SEO spam injections, and total loss of infrastructure integrity. System administrators and security engineers must execute a systematic, forensic-driven recovery protocol to eradicate the threat actor, rebuild compromised components, and implement strict architectural hardening.

Affected environments span the entire WordPress stack: core files, the wp-content directory (comprising themes, plugins, and media uploads), the MySQL/MariaDB database, and the underlying web server configuration (Nginx or Apache). Remediation requires immediate containment, root cause identification, manual or scripted artifact cleansing, and cryptographic validation of all system components.

Root Cause Analysis and Compromise Vectors

Understanding how the compromise occurred is mandatory before initiating restoration. Attack vectors generally fall into four categories:

🚨 Facing an active site error or malware warning?

Chat with an engineer on WhatsApp within 15 minutes.

💬 Chat on WhatsApp
  • Vulnerable Plugins and Themes: Zero-day exploits or unpatched CVEs in third-party plugins allow unauthenticated remote code execution (RCE) or arbitrary file upload vulnerabilities. Attackers upload web shells into wp-content/uploads/ or plugin directories disguised as image files or helper scripts.
  • Stolen Administrative Credentials: Brute-force attacks or credential stuffing campaigns targeting /wp-login.php or the REST API yield administrative access. Once inside, attackers create rogue administrator accounts, install malicious plugins, or modify theme editor files directly through the dashboard.
  • Misconfigured Server Permissions: Overly permissive file and directory permissions (e.g., 777 or 755 on writable files) permit local file inclusion (LFI) and direct modification of core operational files such as index.php, wp-settings.php, and wp-config.php.
  • Database Injections: Persistent SQL injections or direct database manipulation through compromised credentials lead to injected malicious JavaScript payloads within the wp_options table (e.g., siteurl, home, or injected options) and malicious admin users injected into wp_users and wp_usermeta.

During execution, attackers frequently inject obfuscated base64 or eval-based PHP code inside legitimate files or create standalone drop-files designed to accept remote commands. Recovering from such an event requires isolating the host environment, performing deep integrity checks, and executing precise remediation steps.

Step-by-Step Incident Remediation Guide

Execute the following technical steps sequentially via SSH, WP-CLI, and database management interfaces to completely purge malicious artifacts and restore site integrity.

Step 1: Isolate the Environment and Quell Ingress

Immediately disconnect external access to prevent data leakage and lateral movement. If using Nginx, deploy a temporary maintenance page redirecting all traffic except your administrative IP address.

# Nginx configuration snippet for temporary incident isolation
server {
    listen 443 ssl;
    server_name example.com;
    
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    root /var/www/html;

    # Allow only administrator IP
    allow 203.0.113.50;
    deny all;

    location / {
        return 503;
    }

    error_page 503 /maintenance.html;
    location = /maintenance.html {
        root /var/www/html;
    }
}

Step 2: Isolate and Verify Core WordPress Files

Do not attempt to manually clean core WordPress files. Instead, use WP-CLI to verify checksums against the official WordPress repository and replace altered files with pristine versions.

# Navigate to the WordPress root directory
cd /var/www/html

# Run a WP-CLI checksum verification to identify modified core files
wp core verify-checksums --path=/var/www/html

# Re-download and overwrite core files, preserving wp-content and wp-config.php
wp core download --skip-content --force --path=/var/www/html

Step 3: Audit and Clean the wp-content Directory

Attackers frequently hide web shells within theme folders, plugin directories, and upload paths. Execute a recursive scan for unexpected PHP files inside upload directories.

# Find all PHP files hidden inside the uploads directory (none should exist)
find /var/www/html/wp-content/uploads/ -type f -name "*.php" -exec ls -la {} \;

# Remove unauthorized PHP files in uploads
find /var/www/html/wp-content/uploads/ -type f -name "*.php" -delete

# Search for suspicious eval() or base64_decode functions in themes and plugins
grep -rnw '/var/www/html/wp-content/' -e 'eval(' --include=\*.php
grep -rnw '/var/www/html/wp-content/' -e 'base64_decode' --include=\*.php

Step 4: Database Scrubbing and User Audit

Access your MySQL or MariaDB command-line interface to inspect administrative users and scan for injected options or post content.

-- Connect to your WordPress database
mysql -u wordpress_user -p wordpress_db

-- List all users with administrator capabilities
SELECT u.ID, u.user_login, u.user_email, um.meta_value 
FROM wp_users u 
JOIN wp_usermeta um ON u.ID = um.user_id 
WHERE um.meta_key = 'wp_user_level' AND um.meta_value = '10';

-- Remove unauthorized administrator accounts (replace 999 with rogue user ID)
DELETE FROM wp_users WHERE ID = 999;
DELETE FROM wp_usermeta WHERE user_id = 999;

-- Inspect wp_options for injected scripts or malicious options
SELECT option_name FROM wp_options WHERE option_value LIKE '%eval(%' OR option_value LIKE '%base64%';

Step 5: Regenerate Authentication Keys and Salts

Compromised tokens stored in browser cookies or sessions can allow attackers to maintain access even after passwords are changed. Update your wp-config.php security salts immediately.

/**
 * Generate fresh security salts via https://api.wordpress.org/secret-key/1.1/salt/
 * and replace the existing definitions in wp-config.php
 */
define('AUTH_KEY',         'put your unique phrase here');
define('SECURE_AUTH_KEY',  'put your unique phrase here');
define('LOGGED_IN_KEY',    'put your unique phrase here');
define('NONCE_KEY',        'put your unique phrase here');
define('AUTH_SALT',        'put your unique phrase here');
define('SECURE_AUTH_SALT', 'put your unique phrase here');
define('LOGGED_IN_SALT',   'put your unique phrase here');
define('NONCE_SALT',       'put your unique phrase here');

Production Hardening and Edge Cases

Once remediation is complete, you must enforce strict file permissions and server-level rules to prevent reinfection. WordPress files must be owned by the web server user with read-only permissions for all web-facing assets, while write permissions should be tightly restricted.

# Set secure file and directory ownership and permissions
find /var/www/html -type d -exec chmod 755 {} \;
find /var/www/html -type f -exec chmod 644 {} \;

# Restrict permissions on wp-config.php
chmod 400 /var/www/html/wp-config.php

# Assign proper web server user ownership (e.g., www-data for Ubuntu/Nginx)
chown -R www-data:www-data /var/www/html

Disable PHP execution within vulnerable upload directories by adding explicit directives to your Nginx or Apache server blocks.

# Nginx block to disable PHP execution in uploads
location ~* ^/wp-content/uploads/.*\.(php|php5|phtml)$ {
    deny all;
}

When implementing aggressive caching layers (such as Redis object caching or Varnish reverse proxies), ensure that cached malicious output is completely flushed immediately following malware removal. Retain staging backups of both the infected file system and the cleaned database for offline forensic analysis before closing the incident ticket.

Diagnostic Verification and Post-Incident Checklist

Verify that your remediation efforts were successful by cross-referencing system states against the verification matrix below. Continuously monitor server logs and HTTP response codes to ensure operational stability.

Verification Vector Expected State Diagnostic Tool / Command
Core File Integrity Zero modified core files reported wp core verify-checksums
User Account Audit Only authorized administrators present SQL query on wp_usermeta
File Permissions wp-config.php set to 400; directories 755 stat -c "%a %n" /var/www/html/wp-config.php
Upload Execution Block HTTP 403 Forbidden on direct PHP requests in uploads curl -I https://example.com/wp-content/uploads/test.php
Web Server Error Logs Absence of segmentation faults or unauthorized script executions tail -f /var/log/nginx/error.log
SSL / Search Engine Status Clean rating on Google Safe Browsing and VirusTotal API query or manual safety check

Monitor system log files actively at /var/log/nginx/access.log and /var/log/auth.log for abnormal request patterns, POST requests targeting XML-RPC endpoints, or unauthorized SSH login attempts. Establish automated daily integrity monitoring to detect unauthorized file modifications instantly.

Professional WordPress Support & Care

Maintaining a high-performing, secure WordPress site requires continuous monitoring and proactive updates. At SiteSuraksha, our dedicated technical team provides 24/7 security hardening, speed optimization, and hands-on maintenance so you can focus on growing your business.

Follow SiteSuraksha on Google
Add us to your preferred sources for verified WordPress & hosting guides.
FREE 30-SECOND DIAGNOSTIC

Is Your Website Fast & Secure?

Run an instant scan for security vulnerabilities, bloated plugins, and TTFB latency.

🔍 Test Your Site Now →
Map Your Issue to Guaranteed IT Care
Security & Malware
Hacks, 0-day exploits & backup failures
Pro Care (₹5,420/mo) →
Speed & Cloud Bills
Slow checkout, high TTFB & cloud waste
Pro Care (₹5,420/mo) →
ERP & Automation
GST pipelines, RPA & AI support agents
Enterprise (₹14,999/mo) →
EXPERT WORDPRESS CARE

Need Help Securing or Speeding Up Your Site?

Get 24/7 proactive security WAF, daily cloud backups, and sub-second speed optimization from ₹3,470/mo.

💬 Chat on WhatsApp Explore Plans
← Back to All Articles