WordPress Hacked? Here’s How to Fix a Hacked WordPress Site
WordPress Hacked? Here’s How to Secure and Fix Your Compromised Website
Discovering that a WordPress website has been compromised requires immediate, methodical incident response. Attackers frequently exploit vulnerabilities in third-party plugins, outdated core software, misconfigured server permissions, or weak administrative credentials to establish persistence. When a breach occurs, unauthorized code execution can manifest as injected JavaScript redirects, spam-injected database tables, unauthorized administrator accounts, or malicious backdoor scripts embedded deep within the file system.
This technical guide details the exact procedures required to isolate a compromised WordPress installation, eradicate persistent malware, sanitize the MySQL database, and establish a hardened production architecture resistant to future incursions.
Problem Statement & Impact
WordPress compromises typically originate from unpatched Common Vulnerabilities and Exposures (CVEs) in plugins or themes, remote code execution (RCE) via insecure file upload endpoints, or brute-force attacks against administrative interfaces. Once an attacker bypasses authentication boundaries, they typically execute a multi-stage attack:
Chat with an engineer on WhatsApp within 15 minutes.
- Persistence: Creation of hidden backdoor PHP scripts disguised as core components or cached stylesheets.
- Privilege Escalation: Insertion of rogue administrator accounts directly into the
wp_usersandwp_usermetatables. - SEO Spam & Redirection: Modification of rewrite rules and injection of cloaked hyperlinks targeting external malicious domains.
- Resource Abuse: Utilization of server resources for cryptocurrency mining, distributed denial-of-service (DDoS) amplification, or email spam relay.
The business and technical fallout includes blacklisting by search engines and security vendors (such as Google Safe Browsing and Norton), severe brand degradation, loss of customer trust, and potential regulatory liabilities if user Personally Identifiable Information (PII) is exfiltrated. Swift, surgical remediation is mandatory to minimize downtime and prevent long-term domain reputation decay.
Root Cause Analysis & Architecture
Understanding how attackers leverage the WordPress execution lifecycle is essential for effective remediation. WordPress relies on a dynamic request-handling pipeline managed by index.php, which bootstraps the environment via wp-load.php and processes plugins, themes, and database queries.
Attackers often leverage this architecture by executing arbitrary PHP code via injected eval statements or file inclusion vulnerabilities. Common vector points include:
wp-content/uploads/Executable Permissions: Attackers upload malicious PHP files masked as JPEG or PNG payloads. If the web server configuration allows script execution within upload directories, these files can be executed directly via HTTP requests.- Compromised
wp-config.php: Attackers insert database dump routines or remote inclusion URLs at the top or bottom of the configuration file. - Database Object Injection: Serialized PHP objects or base64-encoded payloads stored in the
wp_optionstable (such as active plugin options or rewrite rules) that execute during every page load.
Mitigating these vectors requires resetting file permissions, enforcing strict PHP execution rules at the web server level, and completely rebuilding compromised application layers.
Step-by-Step Implementation & Remediation Guide
Execute the following technical steps sequentially to clean, restore, and harden the WordPress environment.
Step 1: Isolate and Acquire a Forensic Snapshot
Before modifying any files or databases, capture a complete forensic snapshot of the compromised environment. This ensures you retain evidence for root cause analysis if required.
# SSH into your server and create a compressed archive of the web root and database
tar -pczf wp-forensic-backup-$(date +%F).tar.gz /var/www/html
mysqldump -u root -p --all-databases > all-databases-forensic-$(date +%F).sql
Place the application into a restricted maintenance state by deploying a temporary static maintenance page via your web server configuration, preventing further interaction with compromised application scripts.
Step 2: Purge and Reinstall WordPress Core Files
Core file integrity must be verified and restored. Instead of attempting to patch individual files, delete all core PHP files and replace them with verified binaries from the official repository using WP-CLI.
# Navigate to the WordPress root directory
cd /var/www/html
# Remove existing core WordPress files while preserving wp-content and wp-config.php
rm -rf wp-admin wp-includes
rm -f *.php
# Download and extract a fresh, clean copy of the latest WordPress core
wp core download --skip-content --force --allow-root
Step 3: Audit and Clean the wp-content Directory
The wp-content directory houses themes, plugins, and uploads—the most frequent targets for malware injection. Execute these commands to locate suspicious PHP execution within the uploads directory and analyze modified files.
# Find all PHP files hidden inside the uploads directory
find wp-content/uploads/ -type f -name "*.php"
# Find files modified within the last 7 days indicating potential intrusion
find . -type f -mtime -7 -name "*.php"
Review every installed plugin and theme. Delete any inactive, unmaintained, or unrecognized plugins. For active plugins, download fresh vendor distributions and overwrite the existing directories to eliminate backdoors.
Step 4: Sanitize the MySQL Database
Malware frequently persists inside the database. Access your database via the MySQL/MariaDB CLI to inspect and clean suspicious entries.
-- Check for unauthorized administrator users
SELECT ID, user_login, user_email, user_registered FROM wp_users;
-- Inspect user meta for elevated privileges not matching legitimate admins
SELECT * FROM wp_usermeta WHERE meta_key = 'wp_user_level' OR meta_key = 'wp_capabilities';
-- Search for injected scripts inside posts and pages
SELECT ID, post_title, post_type FROM wp_posts WHERE post_content LIKE '%eval(%' OR post_content LIKE '%base64_decode(%';
If unauthorized admin accounts exist, remove them carefully:
-- Example: Delete rogue user ID (replace 99 with target ID)
DELETE FROM wp_users WHERE ID = 99;
DELETE FROM wp_usermeta WHERE user_id = 99;
Step 5: Reset Credentials and Cryptographic Salts
Terminate all active sessions and cut off unauthorized access vectors by resetting authentication tokens and credentials across the entire stack.
- Force a password reset for all legitimate WordPress users.
- Update all SFTP/SSH user credentials and hosting panel passwords.
- Rotate database credentials in
wp-config.phpand the MySQL user grant tables. - Regenerate your WordPress security salts. You can generate fresh keys via the official WordPress API:
# Automatically fetch and replace salts in wp-config.php using WP-CLI
wp config shuffle-salts --allow-root
Step 6: Enforce Strict Server-Level Security Controls
Prevent future execution of untrusted scripts by locking down web server permissions and restricting PHP execution inside upload directories.
If you are running Nginx, add the following location block to your server configuration to disable PHP execution within wp-content/uploads:
location ~* ^/wp-content/uploads/.*\.php$ {
deny all;
}
If you are running Apache, place an .htaccess file inside wp-content/uploads/ with the following directives:
# Disable PHP execution in uploads directory
Deny from all
Production Hardening & Edge Cases
Securing a WordPress installation requires balancing defensive posture with application performance and caching compatibility. When implementing aggressive file permission locking, ensure that automated updates and legitimate plugin operations do not fail.
- File Permissions: Set directory permissions to
755and file permissions to644across the entire installation. Thewp-config.phpfile should be restricted to400or440. - Caching Conflicts: Object caches (such as Redis or Memcached) and full-page caching plugins (such as WP Rocket or LiteSpeed Cache) may serve cached versions of injected malicious scripts. Always flush all server-side and application-level caches immediately after completing a cleanup.
- Object File Ownership: Ensure web server processes (e.g.,
www-data,nginx, orapache) do not own the WordPress root files. Files should ideally be owned by an independent deployment user, with write permissions granted only to specific directories likewp-content/uploads.
Diagnostic Verification & Checklist
Validate the remediation process using the verification matrix below. Execute these validation checks before removing the maintenance page and restoring public access.
| Verification Check | Diagnostic Command / Method | Expected Result |
|---|---|---|
| Core File Integrity | wp core verify-checksums --allow-root |
Success: WordPress installation files check out. |
| Database User Audit | Review wp_users via SQL client |
Only verified, authorized administrators present. |
| Uploads Directory Security | curl -I https://example.com/wp-content/uploads/malicious.php |
HTTP 403 Forbidden or HTTP 404 Not Found. |
| Security Headers Check | curl -I https://example.com |
Presence of CSP, X-Frame-Options, X-Content-Type-Options. |
| Malware Signature Scan | Run updated ClamAV or server security scanner | Zero infected files or known backdoor signatures detected. |
Monitor server access logs (/var/log/nginx/access.log or /var/log/apache2/access.log) continuously post-remediation to identify automated botnets probing for newly patched or remaining vulnerable endpoints.
Is Your Website Fast & Secure?
Run an instant scan for security vulnerabilities, bloated plugins, and TTFB latency.
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.