What to Do When Your WordPress Site Gets Hacked: A Complete Recovery Guide
Discovering your WordPress site has been hacked triggers immediate panic. Defaced homepage displaying profanity, search results redirecting to malware sites, hosting provider suspension notices, or Google Safe Browsing warnings announce devastating reality: your site was compromised, data potentially stolen, and visitor trust destroyed. The minutes following hack discovery determine whether you recover quickly with minimal damage or spiral into weeks of cleanup, SEO penalties, and reputation destruction.
WordPress powers 43% of all websites, making it the primary target for automated hacking campaigns scanning millions of sites hourly for vulnerabilities. Most WordPress hacks result from outdated plugins, weak passwords, or shared hosting compromises rather than sophisticated targeted attacks. Understanding this reality reduces panic while enabling systematic recovery. This comprehensive guide provides step-by-step recovery procedures transforming hacked WordPress sites back into secure, clean installations while minimizing data loss, downtime, and long-term consequences.
Immediate Response: First 30 Minutes After Discovery
Your actions in the first 30 minutes after discovering a hack determine recovery difficulty and damage severity. Follow these immediate response steps before attempting cleanup or restoration.
Take Site Offline Immediately
Enable maintenance mode or password protection: Prevent visitors from accessing compromised site immediately. Hacked sites often serve malware to visitors, transmit stolen data to attackers, or display content damaging your reputation. Every visitor to compromised site represents potential victim and further reputation damage.
Access hosting control panel and enable maintenance mode through server configuration. Most hosting providers offer "coming soon" or "maintenance mode" settings displaying placeholder page while preventing access to WordPress installation. Alternatively, password-protect entire site directory through .htaccess authentication requiring HTTP basic auth credentials for access.
If you cannot access hosting control panel because credentials were changed by attackers, contact hosting support immediately requesting emergency site suspension. Explain security compromise and request temporary site disable while you regain access and begin cleanup procedures.
Document everything visible about the hack: Before making any changes, document hack evidence thoroughly. Take screenshots of defaced pages, malicious redirects, or suspicious admin dashboard elements. Copy any attacker messages, ransom demands, or defacement signatures. Record exact time you discovered compromise and any unusual site behavior preceding discovery.
This documentation serves multiple purposes: evidence for law enforcement if needed, reference for security analysis identifying attack vectors, and proof for hosting providers, security services, or insurance claims. Without documentation, determining hack scope and attack methods becomes significantly harder during recovery process.
Change All Passwords and Access Credentials
Update hosting account credentials first: Change your hosting account password immediately through provider's account recovery system. Use completely new password unrelated to any previous passwords. Enable two-factor authentication on hosting account if available. Hosting account compromise enables attackers to reinstall malware even after WordPress cleanup.
Change FTP, SFTP, and SSH credentials through hosting control panel. Attackers often create additional FTP accounts for persistent access. Review all FTP user accounts, delete any you don't recognize, and change passwords on legitimate accounts. Revoke SSH keys and generate new key pairs if you use SSH authentication.
Reset database passwords: Change MySQL or MariaDB database password through hosting control panel or database management interface. Update wp-config.php with new database password after changing it. Database access enables attackers to inject malicious code, create admin accounts, or steal sensitive information even without file system access.
Change WordPress admin passwords: If you can access WordPress admin dashboard, change all administrator account passwords immediately. Use strong randomly generated passwords stored in password manager. If admin access is blocked, reset passwords through phpMyAdmin by directly updating wp_users table password fields with new MD5 hashes.
Assess Damage and Identify Attack Vector
Check file modification timestamps: Access server via FTP, SFTP, or file manager and sort files by modification date. Files modified recently that you didn't change yourself indicate attacker modifications. Common targets include wp-config.php, .htaccess, index.php in root and wp-admin directories, and files in wp-content/uploads.
Download copies of recently modified suspicious files to local computer for analysis before making changes. These files help identify attack methods and malware types during cleanup. Compare suspicious files against fresh WordPress downloads to identify injected malicious code.
Review access logs for suspicious activity: Download server access logs through hosting control panel. Search for unusual patterns like repeated requests to wp-login.php indicating brute force attempts, requests to wp-admin/install.php suggesting installation exploit attempts, or POST requests to plugin files indicating exploitation.
Identify IP addresses associated with suspicious activity. Check if these IPs appear in threat databases or blocklists. Note geographic locations of attacking IPs and times of suspicious requests. This information helps understand attack timeline and methods used for compromise.
Check for unauthorized admin accounts: Access WordPress admin (if possible) or database directly through phpMyAdmin. Query wp_users table for all accounts with administrator privileges: SELECT * FROM wp_users WHERE ID IN (SELECT user_id FROM wp_usermeta WHERE meta_key = 'wp_capabilities' AND meta_value LIKE '%administrator%').
Delete any administrator accounts you don't recognize immediately. Attackers create admin accounts with innocuous names like "support," "backup," or "service" for persistent access. These accounts remain functional even after password changes, allowing attackers to regain control after cleanup attempts.
Malware Detection and Removal
Identifying and removing all malicious code represents the most critical and challenging recovery phase. Incomplete malware removal enables attackers to quickly reinfect cleaned sites.
Scan Files for Malware Signatures
Use command-line malware scanning: If you have SSH access, use grep to search for common malware patterns. Search for base64_decode usage: grep -r "base64_decode" /path/to/wordpress/ --include="*.php". Legitimate WordPress rarely uses base64_decode; extensive usage often indicates obfuscated malware.
Search for eval functions: grep -r "eval(" /path/to/wordpress/ --include="*.php". The eval function executes arbitrary PHP code and is primary mechanism for malware execution. Review every file containing eval; most represent malicious code injection.
Search for suspicious file operations: grep -r "file_put_contents\|fwrite\|fopen" /path/to/wordpress/ --include="*.php" | grep -i "base64\|eval\|assert". These patterns indicate malware creating additional malicious files or backdoors for persistent access.
Scan with security plugins: Install fresh WordPress security plugin through manual FTP upload rather than WordPress admin to ensure clean plugin files. Wordfence, Sucuri Security, or MalCare provide malware scanning functionality. Run comprehensive scan examining all files, database tables, and configurations.
Security plugins compare your WordPress files against known-good versions from WordPress.org repository, identifying modifications. They also check for known malware signatures, backdoors, and suspicious code patterns. Review scan results carefully; not all detected items are malicious, but investigate each flagged file.
Clean WordPress Core Files
Replace core files with fresh downloads: The safest approach to cleaning compromised WordPress core files is complete replacement. Download fresh WordPress package matching your current version from wordpress.org/download/releases/. Extract archive to local computer.
Delete all existing WordPress core files and directories from server except wp-content directory and wp-config.php file. Upload fresh WordPress core files extracted from clean download. This ensures zero contamination in core files while preserving your content, plugins, themes, and configuration.
Verify wp-config.php wasn't modified by comparing against backup or checking for suspicious code additions. Malware frequently adds code to wp-config.php for automatic execution on every page load. Remove any code you don't recognize or that doesn't match standard wp-config.php structure.
Update .htaccess to clean version: Backup current .htaccess file, then replace with clean default WordPress .htaccess or regenerate through Settings Permalinks in WordPress admin. Hackers inject malicious redirects, backdoor access, or script execution permissions through .htaccess modifications.
Compare your backed-up .htaccess against clean version to identify malicious additions. Common malware patterns include RewriteRule redirecting search engine visitors to malware sites, PHP execution enabled in upload directories, or base64-encoded configuration blocks.
Clean Plugins and Themes Thoroughly
Delete and reinstall all plugins: Download fresh versions of all currently installed plugins from WordPress.org or developers' official sites. Delete existing plugin directories completely through FTP rather than WordPress admin deactivation. Upload fresh clean plugin files and reactivate after verifying file integrity.
For premium or custom plugins unavailable from WordPress.org, contact developers for clean downloads. If clean versions are unavailable or plugins are abandoned, find alternative maintained plugins providing similar functionality rather than continuing to use compromised code.
Avoid "cleaning" malware from plugins through manual code editing. Malware spreads through multiple files using obfuscation, making complete manual removal nearly impossible. Fresh reinstallation guarantees clean code more reliably than attempted manual cleanup.
Replace theme files with fresh versions: Download clean version of your active theme from theme developer or WordPress.org theme repository. Delete existing theme directory and upload fresh version. Reapply any customizations from backups or notes rather than keeping potentially contaminated theme files.
For child themes with custom code, carefully review all custom PHP files for malicious injections. Malware targets child theme functions.php for code injection since child themes execute on every page load. Compare your child theme code against your development backups to identify unauthorized additions.
Database Cleaning and Security
Malware frequently injects code into WordPress database, enabling persistence even after file cleanup. Thorough database cleaning is essential for complete malware removal.
Scan Database for Malicious Code Injections
Search wp_posts for injected content: Access database through phpMyAdmin. Search wp_posts table for common malware patterns. Execute query: SELECT * FROM wp_posts WHERE post_content LIKE '%iframe%' OR post_content LIKE '%base64%' OR post_content LIKE '%eval(%'. Review results for unauthorized iframes, encoded scripts, or eval functions injected into post content.
Malware commonly injects hidden iframes loading malware from external sites or injects redirects stealing search engine traffic. These injections are often invisible to site visitors but detected by search engines, causing Safe Browsing warnings or search ranking penalties.
Check wp_options for backdoor code: Examine wp_options table for malicious entries. Query: SELECT * FROM wp_options WHERE option_value LIKE '%base64%' OR option_value LIKE '%eval(%' OR option_value LIKE '%assert(%'. Malware stores backdoor code, configuration data, or communication scripts in options table for persistent execution.
Review suspicious options carefully. Some legitimate plugins use base64 encoding for configuration storage, but eval or assert functions in options indicate malware. Delete malicious options after backing up database. Test site functionality after deletions to ensure no legitimate functionality broke.
Inspect widget and menu settings: Check wp_options table entries for widgets and nav_menu_options. Malware injects malicious JavaScript or PHP into widgets displayed on every page. Query: SELECT * FROM wp_options WHERE option_name LIKE '%widget%' AND (option_value LIKE '%script%' OR option_value LIKE '%eval%').
Remove Malicious Database Users and Content
Delete unauthorized administrator accounts: Query wp_users and wp_usermeta tables to find all administrator accounts. Delete accounts you don't recognize using query: DELETE FROM wp_users WHERE ID = [suspicious_user_id]. Also delete associated metadata: DELETE FROM wp_usermeta WHERE user_id = [suspicious_user_id].
Change usernames for remaining administrator accounts if attackers might know current usernames. Create new admin account with different username, transfer all content attribution to new account, then delete old admin account. This prevents attackers from targeting known administrator usernames.
Clean spam injections from posts and comments: Hackers inject spam links into existing posts and pages to manipulate search rankings or redirect traffic. Review recent posts for unexpected link additions or content modifications. Check post revision history to identify when unauthorized changes occurred.
Delete obvious comment spam using bulk selection in WordPress admin or database queries. Query: DELETE FROM wp_comments WHERE comment_approved = 'spam' removes all comments already marked spam. For massive spam floods, delete all comments newer than compromise date if rebuilding legitimate comments is easier than cleaning spam.
Update Security Keys and Database Credentials
Generate new WordPress authentication keys: Visit api.wordpress.org/secret-key/1.1/salt/ to generate fresh random keys. Replace all eight key definitions in wp-config.php including AUTH_KEY, SECURE_AUTH_KEY, LOGGED_IN_KEY, NONCE_KEY and their corresponding SALT values.
New keys invalidate all existing login sessions, forcing attackers out of compromised accounts. All users must log in again with credentials after key regeneration. Combined with forced password resets, this completely revokes all existing authentication.
Change database table prefix: If your database uses default wp_ prefix, consider changing to random prefix. While not direct malware removal, prefix changes make automated reinfection attempts harder. Use plugin like iThemes Security or manually rename tables through phpMyAdmin, updating prefix in wp-config.php.
Overwhelmed by Malware Removal Complexity?
Hacked WordPress site recovery requires deep technical expertise, careful database manipulation, and thorough malware analysis. Missing even single backdoor file enables rapid reinfection after cleanup efforts. The stress of managing recovery while your site remains offline and reputation suffers compounds difficulty.
Consider alternative recovery approach: restore your WordPress site from clean archived version predating the compromise. ReviveNext recovers WordPress sites from Wayback Machine archives, providing clean pre-hack versions of your content, structure, and design. Skip malware removal complexity and start fresh with archived version from when your site was secure.
Post-Cleanup Security Hardening
After removing malware and cleaning infected files, implement comprehensive security hardening preventing reinfection and strengthening defenses against future attacks.
Update All Software to Latest Versions
Update WordPress core to latest release: Outdated WordPress versions contain publicly known vulnerabilities enabling easy compromise. Update to latest WordPress release immediately after malware cleanup. Test updates in staging environment first if site uses complex custom code potentially breaking during updates.
Enable automatic WordPress core updates by adding define('WP_AUTO_UPDATE_CORE', true); to wp-config.php. This ensures critical security updates apply automatically between manual maintenance sessions, reducing vulnerability window when critical security releases occur.
Update all plugins and themes: Update every plugin and theme to latest available version. Delete any plugins or themes you don't actively use, even if currently deactivated. Deactivated plugins still contain code and vulnerabilities attackers can exploit.
Review each plugin's recent update changelog for security fixes. Plugins patching security vulnerabilities in recent updates likely contributed to your compromise if you were running outdated versions. Prioritize keeping these plugins current with automatic updates if available.
Implement Strong Access Controls
Enforce strong password policy: Install plugin requiring strong passwords for all users. Force password reset for every user account, requiring new passwords meet minimum length, complexity, and strength requirements. Weak passwords remain primary WordPress compromise vector.
Require minimum 16-character passwords including uppercase, lowercase, numbers, and symbols. Prohibit common passwords, dictionary words, and passwords containing username or site name. Modern WordPress includes built-in password strength checker enforcing these requirements during password creation.
Enable two-factor authentication: Install two-factor authentication plugin like Wordfence Login Security or Google Authenticator. Require 2FA for all administrator accounts immediately. Encourage 2FA for editor accounts. Two-factor authentication prevents unauthorized access even if passwords are compromised through breaches or brute force.
Limit login attempts: Install login security plugin limiting failed login attempts from single IP address. Configure automatic temporary IP blocking after 3-5 failed login attempts within 30 minutes. This prevents brute force attacks systematically testing password combinations.
Configure File and Directory Permissions
Set correct WordPress file permissions: Access server via SSH and execute: find /path/to/wordpress/ -type d -exec chmod 755 {} \; to set all directories to 755. Then: find /path/to/wordpress/ -type f -exec chmod 644 {} \; for all files.
Set wp-config.php to 400 or 440 permissions: chmod 400 wp-config.php. This restrictive permission prevents unauthorized viewing or modification of database credentials and security keys while allowing PHP to read configuration.
Prevent PHP execution in uploads directory: Create .htaccess file in wp-content/uploads directory blocking PHP execution. Add content: deny from all followed by <FilesMatch "\.(jpg|jpeg|png|gif|pdf)$"> allow from all </FilesMatch>. This prevents execution of malicious PHP files uploaded through compromise while allowing legitimate media access.
Search Engine and Reputation Recovery
Security compromise often triggers search engine penalties, Safe Browsing warnings, and reputation damage requiring specific recovery steps beyond malware cleanup.
Request Google Safe Browsing Review
Fix all malware before requesting review: Google Safe Browsing warnings appear when Google detects malware, phishing, or deceptive content on your site. Before requesting review, ensure complete malware removal and security hardening. Requesting review while malware remains results in review rejection and delayed recovery.
Use Google Search Console Security Issues report to identify specific pages Google flagged for malware. Review each flagged page carefully, verifying complete cleanup. Run multiple malware scans with different tools ensuring thorough detection.
Submit reconsideration request: Access Google Search Console and navigate to Security Issues section. After confirming all malware removal, submit request for review. Provide detailed explanation of actions taken to clean site and prevent future compromises including security measures implemented.
Google typically reviews reconsideration requests within 72 hours for malware issues. If review indicates remaining malware, repeat cleanup process addressing any specified issues before submitting subsequent review request.
Address Search Ranking Recovery
Monitor search traffic and rankings: Hacks causing spam injections, hidden links, or doorway pages often trigger Google algorithm penalties or manual actions reducing search rankings. Monitor Google Search Console for manual actions requiring reconsideration requests.
Track search traffic through Google Analytics or Search Console performance reports. Significant traffic drops following compromise indicate search ranking penalties. Recovery typically requires thorough cleanup, manual action reconsideration requests, and time for search engines to recrawl and reassess site quality.
Submit updated sitemap: After cleaning malware and verifying all content legitimacy, generate fresh XML sitemap and submit to Google Search Console. Request crawling of important pages through URL Inspection tool to accelerate clean content indexing.
Rebuild Visitor Trust
Communicate with users transparently: For sites with user accounts or customer relationships, send email notification explaining security incident, steps taken to resolve compromise, and measures implemented to prevent future incidents. Transparency builds trust while silence breeds suspicion.
Explain what data might have been exposed, recommendations for users to protect themselves like password changes, and assurances about current site security. Avoid minimizing incident severity or blaming users, which damages credibility.
Monitor for reinfection indicators: Install security monitoring plugin providing continuous malware scanning and file integrity monitoring. Configure email alerts for file changes, new admin accounts, or detected malware. Monitor site behavior daily for several weeks following cleanup, watching for reinfection signs.
Prevention: Stopping Future Compromises
Recovery from hack requires substantial effort. Implementing preventive measures costs fraction of recovery effort while dramatically reducing future compromise probability.
Establish Regular Maintenance Schedule
Weekly security reviews: Schedule weekly maintenance window reviewing available updates, security advisories, and site security posture. Apply plugin updates after reading changelogs for security fixes. Run security scans weekly detecting emerging threats promptly.
Monitor failed login attempts, user account changes, and file modifications through security plugin logs. Regular monitoring enables rapid detection of compromise attempts before they succeed or immediately after initial breach before major damage occurs.
Automated daily backups: Configure automated backup solution creating daily database backups and weekly full file backups. Store backups in off-site location like cloud storage, never exclusively on same server as WordPress installation.
Test backup restoration quarterly in staging environment verifying backup integrity and restoration procedure accuracy. Untested backups frequently fail when needed most, during actual emergencies.
Deploy Web Application Firewall
Use cloud-based WAF service: Consider services like Cloudflare, Sucuri, or Wordfence Cloud providing web application firewall filtering malicious traffic before it reaches your WordPress installation. WAF blocks common attack patterns including SQL injection, cross-site scripting, and malware upload attempts.
WAF services include DDoS protection, automatic malware scanning, and virtual patching providing temporary protection for vulnerable plugins until official patches release. Cloud-based WAF reduces server load while providing comprehensive protection layer.
Conduct Security Audits
Quarterly professional security assessment: For business-critical WordPress sites, engage security professional conducting quarterly penetration testing and security audits. Professional assessment identifies vulnerabilities before attackers exploit them.
Review third-party services, plugins, and themes for security track records before installation. Check WPScan Vulnerability Database for known issues. Choose actively maintained software with responsive developers patching security issues promptly.
Conclusion: Recovery and Resilience
WordPress hack discovery triggers panic, but systematic recovery approach transforms catastrophe into manageable challenge with defined resolution path. Immediate response actions including site shutdown, password changes, and damage assessment prevent additional compromise and preserve evidence for cleanup.
Thorough malware removal through file replacement, database cleaning, and comprehensive scanning eliminates attacker access and malicious code. Post-cleanup hardening including software updates, strong access controls, and file permissions prevents immediate reinfection.
Search engine and reputation recovery through Safe Browsing reviews, ranking monitoring, and transparent communication rebuilds trust and restores search visibility. Prevention through regular maintenance, backup strategies, and security monitoring reduces future compromise probability to minimal levels.
Every WordPress site faces persistent attack attempts. Security isn't achieved through perfection but through defense layers making successful compromise difficult and rapid recovery possible. Implement comprehensive security measures, maintain vigilant monitoring, and prepare thorough recovery procedures before incidents occur.
Your hacked WordPress site can recover completely with systematic cleanup and prevention implementation. Follow this guide methodically, prioritizing thoroughness over speed. Incomplete cleanup enables rapid reinfection, wasting recovery efforts. Invest time in comprehensive security hardening now, preventing future incidents requiring repeated recovery procedures.
Related Articles
WordPress Malware Removal: Complete Cleanup and Prevention Guide
WordPress site infected with malware? This comprehensive guide covers detection, manual removal, automated scanning tools, database cleaning, and security hardening to prevent reinfection.
Is Your Restored WordPress Site Secure? Post-Recovery Security Checklist
Just restored your WordPress site? Don't go live without completing this essential security checklist. Protect your recovered site from immediate re-compromise with these critical security measures.
Ready to Restore Your Website?
Restore your website from Wayback Machine archives with full WordPress reconstruction. No credit card required.