Your WordPress Site is Hacked? Follow These 16 Steps to Remove Malware Forever
WordPress malware infections happen to 1 in 3 websites. If your site is compromised, you're losing traffic, damaging your reputation, and risking customer data theft. This comprehensive guide walks you through the exact 16-step process security professionals use to remove malware, clean databases, eliminate backdoors, and prevent re-infection. Learn detection methods, removal techniques, and hardening strategies. Get your site back online safely and securely.
How to Remove Malware from WordPress: Complete Step-by-Step Guide
---
Introduction: Why WordPress Malware is a Growing Threat
WordPress powers over 43% of all websites on the internet, making it the most popular content management system globally. However, this popularity also makes it a prime target for cybercriminals. If you've discovered that your WordPress site has been compromised by malware, you're not alone.
Every day, thousands of WordPress websites fall victim to malicious code injections, backdoors, and ransomware attacks. The consequences can be devastating: your site gets blacklisted by Google, visitors experience suspicious redirects, or worse—your sensitive business data gets stolen.
The reality? Most WordPress malware infections happen due to:
- Outdated plugins and themes
- Weak admin credentials
- Unpatched WordPress core vulnerabilities
- Compromised hosting accounts
- Social engineering attacks
In this comprehensive guide, I'll walk you through the exact step-by-step process I use to remove malware from WordPress sites. Prefer to have an expert handle it? Hire me to clean your WordPress site—I've removed malware from 500+ sites since 2015. Whether you're a beginner or have some technical experience, you'll learn actionable techniques to clean your site and prevent future infections.
What you'll learn in this guide:
- How to identify different types of malware that target WordPress
- Complete detection methods to find infections on your site
- Step-by-step preparation before starting removal
- The systematic removal process used by security professionals
- Advanced techniques for severe infections
- How to prevent future infections with a security fortress
- When to hire professional help for complex situations
---
Part 1: Understanding WordPress Malware Types
What Types of Malware Target WordPress?
Before jumping into removal, understanding what you're dealing with is critical. WordPress malware comes in several forms, each requiring slightly different removal approaches:
1. Backdoors: The Persistent Threat
Backdoors are hidden access points that allow attackers to regain access to your site even after the initial vulnerability is patched. Think of them like a secret entrance thieves use even after you've locked the front door. They're often injected as small PHP files hidden in obscure directories and are programmed to create new admin accounts or allow remote execution of commands.
Example locations where backdoors hide:
/wp-content/uploads/.htaccess- Hidden in media directory where admins rarely check/wp-includes/wp-load-temp.php- Disguised within WordPress core files/wp-admin/includes/admin-backdoor.php- Nested in admin directories/wp-content/cache/[random-name].php- Hidden in cache directories- Root directory files like
/shell.phpor/tmp/loader.php
Real-world example: I once found a backdoor that automatically created a new admin account every 24 hours. Even after removal, the site got re-infected within hours because the backdoor was still active. This is why thorough scanning is essential.
Detection indicators:
- Unexpected new files in WordPress directories
- Files with timestamps newer than your last WordPress update
- PHP files in the uploads directory (which shouldn't contain code)
- Unusual file names like
wp-tmp.php,index2.php, or random letter combinations
2. Web Shells: The Remote Control Panel
Web shells are malicious scripts that give hackers complete control over your server. They essentially provide a browser-based command line interface that allows remote code execution, file manipulation, database access, and complete server compromise.
Common symptoms of web shell infection:
- Unexpected new admin users appearing in your WordPress user list
- Strange database queries consuming server resources
- Unusual CPU usage spikes and server slowdowns
- Outbound network traffic to unknown IP addresses
- Your hosting provider reporting suspicious activity
- Server running out of disk space inexplicably
Where web shells typically hide:
/wp-content/plugins/abandoned-plugin/shell.php(in outdated plugins)/wp-content/themes/child-theme/admin-panel.php(in theme files)/uploads/2024/01/image.php(disguised as image files)- Database as serialized data in option tables
- Compressed
.tar.gzor.zipfiles in the uploads directory
Real impact: A web shell can allow attackers to steal your customer databases, inject ransomware, use your server to attack other websites, or harvest cryptocurrency using your server resources. The damage goes beyond your WordPress site to your entire hosting account.
3. Injected Content (SEO Spam): The Invisible Parasite
This type injects spam links and keywords into your WordPress database or files, harming your SEO rankings and redirecting users to malicious sites. You might not even notice it because it's often invisible to regular site visitors but visible to search engines.
Where injected content hides:
- Database posts and pages with hidden text using
display: none;CSS - Post metadata and post revisions containing spam links
- Theme footer files with cloaked redirect scripts
- .htaccess redirects that only activate for search engine bots
- Category and tag descriptions
- Image alt text and file names
- Widget content in sidebar areas
How to identify it:
- Your Google rankings drop suddenly
- Google Search Console shows indexed pages you didn't create
- Manual inspection reveals hidden text using browser developer tools
- Redirect scripts in footer files or functions.php
- Suspicious links pointing to casinos, pharmaceuticals, or betting sites
Real-world scenario: One client's site was showing 10,000+ indexed spam pages in Google. Search Console showed massive amounts of injected content invisible to the naked eye. This tanked their rankings and damaged their brand reputation.
4. Ransomware: The Ultimate Threat
The most dangerous type of malware—it encrypts your files and demands payment for decryption. This is a critical threat because it can completely destroy your business operations within hours.
How ransomware typically works:
- Attacker gains access (usually through compromised plugin or weak credentials)
- Ransomware is uploaded and executed
- All important files are encrypted with military-grade encryption
- A ransom note appears demanding payment in Bitcoin
- Your site goes completely offline and inaccessible
Prevention is crucial because:
- Ransomware cannot be decrypted without the attacker's private key
- There's no guarantee paying will get you the decryption key
- Even if you pay, attackers often don't provide the key
- Your data may have been copied before encryption
Types of ransomware targeting WordPress:
- WP Locker - Encrypts WordPress database
- Jokeroo - Encrypts entire file system
- BadBlock - Locks users out and demands payment
5. Adware and PUPs (Potentially Unwanted Programs)
These inject advertisements or redirect users to affiliate sites, generating unauthorized revenue from your site's traffic. PUPs are technically not malicious but are unwanted software bundled with legitimate programs.
Common characteristics:
- Pop-up ads appearing on your site that you didn't add
- Users redirected to affiliate links for products
- Browser toolbars and extensions appearing on user computers
- Modified search results
- Redirect pages appearing before reaching your actual content
How they harm your site:
- Users perceive your site as unprofessional
- Search engines penalize sites with excessive ads
- Users leave your site due to poor experience
- Ad revenue goes to attackers, not you
- Your site reputation suffers
---
Part 2: How to Detect Malware on Your WordPress Site
Detection is your first line of defense. The earlier you identify malware, the less damage it can cause. There are multiple detection methods, and using several together gives you the most comprehensive picture of what types of malware may be affecting your site.
Important: If you discover malware using these detection methods, proceed immediately to Part 3: Preparing for Malware Removal before taking any action.
Step 1: Run a Security Scan with WordPress Security Plugins
The easiest first step is using a security plugin to scan your WordPress installation. These plugins have signature databases of known malware and heuristic engines to detect unknown threats.
Recommended free security plugins:
Wordfence Security
- Real-time malware scanning and comprehensive security features
- Signature-based detection of 5M+ known malware samples
- File integrity monitoring to detect changes
- Login attempt tracking and brute-force protection
- Firewall rules and IP reputation checking
- Free version suitable for small sites; premium adds advanced features
Sucuri Security
- Provides free malware detection and website monitoring
- Post-infection cleanup guidance
- Malicious URL detection
- Blacklist monitoring (Google, Bing, etc.)
- Built-in security audits
- Integration with Sucuri's cloud-based WAF (Web Application Firewall)
All In One WP Security & Firewall
- Beginner-friendly with solid scanning capabilities
- File permissions checking
- Database table prefix verification
- User login monitoring
- Less resource-intensive than Wordfence
- Good for sites with limited server resources
How to use security plugins effectively:
- Install the security plugin from the WordPress plugin repository
- Navigate to the plugin's scan section
- Run a full security scan (not quick scan) - this takes longer but is thorough
- Let it scan all files, not just WordPress core
- Review the detailed report for detected threats
- Document all findings before taking action
- Save the scan report to your computer for records
Important: Different plugins detect different threats. If one plugin passes a site clean, run a second scan with a different plugin for confirmation. I've seen cases where Wordfence detected threats that Sucuri missed, and vice versa.
Pro Tip: If your site is already showing suspicious behavior or WordPress won't load properly, use a third-party scanning service like Wordfence.com or Sucuri.net which can scan even if plugins are disabled. These services scan your site from their servers without needing plugin installation.
Step 2: Check Your Google Search Console for Warnings
Google regularly scans websites and flags those containing malware. Google's detection system is sophisticated and often catches malware that hasn't yet been detected by WordPress security plugins.
To check for Google warnings:
- Go to Google Search Console
- Sign in with the Google account associated with your site
- Select your property from the dropdown
- Look for any red warning triangle or "Security Issues" section in the left sidebar
- Click on "Security Issues" to view details
- Google will specify:
- The type of malware detected
- Sample URLs containing malware
- When Google first detected it
- Pages indexed with malware
- Recommended actions
What Google's warnings mean:
- Malware found: Your site contains harmful software (viruses, trojans, spyware)
- Deceptive site found: Your site contains phishing or social engineering content
- Unwanted software found: Your site contains adware, PUPs, or unwanted programs
This gives you concrete evidence of malware and the specific URLs affected. Google's detection is often accurate, though it can sometimes have false positives. Use this as one data point among several detection methods.
Action if Google flags your site:
- Don't panic—many legitimate sites get flagged
- Thoroughly clean your site (follow this guide)
- Request a review in Search Console once cleaned
- Google typically responds within 24-72 hours
- If declined, clean more thoroughly and resubmit
Step 3: Check Your Hosting Control Panel Logs
Your hosting provider's control panel (cPanel, Plesk, Directadmin) contains logs that reveal suspicious activity.
What to check:
Error Logs:
- Navigate to your control panel's "Error Log" or "Raw Access Log"
- Look for 500 errors from unusual files
- Check for repeated failed login attempts
- Identify suspicious file access patterns
Access Logs Analysis:
# Look for patterns like:
POST /wp-admin/admin-ajax.php?action=exploit
GET /wp-content/uploads/shell.php
GET /wp-includes/wp-load.php?cmd=whoami
GET /index.php?page=../../../../../../../../etc/passwd
Detailed log analysis (requires technical knowledge):
# Find suspicious POST requests
grep "POST" /home/username/access_log | grep -E "(shell|cmd|exec|eval)" | head -20
# Find unusual file access
grep -E "\.(php|phtml|php3|php4|php5)" /home/username/access_log | grep uploads
# Find 403/404 errors (potential exploitation attempts)
grep " 40[34] " /home/username/access_log | tail -100
Warning signs in logs:
- Repeated requests to non-existent files
- POST requests to admin-ajax.php with suspicious parameters
- Requests to execute commands (cmd, exec, system, shell_exec)
- Base64-encoded data in URLs (often obfuscated malware)
- Requests from unusual geographic locations
- Spike in traffic from single IP address
Step 4: Examine Your Website's Backend Manually
Sometimes malware hides from automated scanners through obfuscation or novel techniques. Manual inspection is essential for thorough detection.
Check for suspicious admin users:
- Log in to WordPress admin
- Navigate to Users → All Users
- Look for unfamiliar accounts with admin privileges
- Check "Date Added" column for recent additions
- Note any users you don't recognize
- Hover over usernames to see their email addresses—check if they're legitimate
Real-world red flags:
- Admin account named "administrator2" or similar variations
- User accounts with suspicious emails (gmail accounts when you use business emails)
- Admin users created on dates you didn't make changes to the site
- Users with generic names like "test," "admin1," or random characters
Examine installed plugins:
- Go to Plugins → Installed Plugins
- Verify you recognize each one
- Check plugin descriptions and author names
- Look for:
- Plugins you don't remember installing
- Plugins with vague descriptions or no description
- Plugins with unusual author names or no author listed
- Plugins that haven't been updated in years
- Plugins with low ratings or warnings
Check for unknown themes:
- Navigate to Appearance → Themes
- Review all installed themes, not just the active one
- Look for:
- Themes you don't recognize
- Themes with suspicious names
- Themes without author information
- Child themes that seem unnecessary
Inspect theme files for modifications:
- Connect via SFTP (recommended) or File Manager
- Navigate to
/wp-content/themes/your-active-theme/ - Open
functions.php,header.php,footer.phpin a text editor - Look for:
- Unfamiliar function definitions
eval()orbase64_decode()functions- Suspicious includes or requires
- Code you didn't write
- Code comments in different style than the rest
- Compare files with a fresh download of the same theme version from WordPress.org
Check .htaccess file for redirects:
- Connect via SFTP
- Navigate to your WordPress root directory
- Download
.htaccessfile (it may be hidden by default) - Open in text editor and look for:
- RewriteRules you don't recognize
- Redirect rules to external sites
- Conditions that only apply to search engines
- Complex rules that seem obfuscated or intentionally confusing
Examine wp-config.php:
- Open
/wp-config.phpin a text editor - Look at the end of the file for:
- Additional includes or requires
- Unfamiliar code after the final
?> - SQL queries being executed
- Suspicious variable definitions
---
Part 3: Preparing for Malware Removal
Preparation is essential before beginning removal. A single mistake during cleanup can damage your WordPress installation irreparably. Take time to follow these steps carefully. Once you've confirmed malware detection and completed preparation, you'll be ready for the systematic removal process.
Step 4: Take a Full Backup Before Starting
Critical: This is non-negotiable. If something goes wrong during removal, you need a recovery point. This backup serves as your safety net.
Why backups matter:
- Accidental file deletion during cleanup
- Database corruption from manual SQL queries
- Removal tools causing unintended damage
- Need to recover specific files or data
- Documentation of original infection for forensics
Backup your WordPress site using multiple methods:
Option A: Using a Backup Plugin (Easiest for Beginners)
- Install UpdraftPlus or BackWPup from WordPress plugin repository
- Configure the plugin settings:
- Enable database backup
- Enable file backup (including uploads, themes, plugins)
- Choose backup destination (cloud storage like Dropbox, Google Drive, or Amazon S3)
- Create a full backup immediately
- Download the backup ZIP file to your local computer
- Store backup copies in at least two secure locations:
- External hard drive
- Cloud storage (encrypted)
- USB drive kept in safe location
Option B: Using cPanel File Manager (Hosting Control Panel)
- Log in to your hosting control panel (cPanel, Plesk, or similar)
- Go to File Manager
- Navigate to your WordPress root directory (usually
/public_html/or/home/username/public_html/) - Select all WordPress files
- Right-click and select "Compress" or "Create Archive" to create a backup ZIP
- Download the compressed file to your computer
- Export your database separately:
- Go to phpMyAdmin
- Select your WordPress database
- Click "Export"
- Choose "Quick" export format
- Save the SQL file
Option C: Using SSH/Command Line (Most Reliable)
# Create file backup
tar -czf wordpress-backup-$(date +%Y%m%d).tar.gz /path/to/wordpress
# Backup database (replace values with your actual credentials)
mysqldump -u wordpress_user -p wordpress_database > wordpress-db-$(date +%Y%m%d).sql
# Verify backup files were created
ls -lh wordpress-backup-*.tar.gz wordpress-db-*.sql
Backup verification checklist:
- [ ] Database backup file downloaded and verified (should contain SQL statements)
- [ ] WordPress files backup downloaded
- [ ] Backup stored in multiple locations
- [ ] You know exactly where your backups are stored
- [ ] Backup is not stored on the compromised server (dangerous if ransomware strikes)
Step 5: Disable Public Access While Cleaning
Put your site in maintenance mode to prevent visitors from accessing infected content during cleanup. This is critical for several reasons:
Why maintenance mode is essential:
- Prevents users from experiencing malicious redirects or attacks
- Stops search engines from indexing infected content
- Prevents malware from being distributed to site visitors
- Protects your site's reputation during cleanup
- Allows you to work without worrying about live traffic
Method 1: Using a Maintenance Mode Plugin (Recommended)
- Install "Maintenance Mode" or "WP Maintenance Mode" plugin
- Activate the plugin
- Go to plugin settings
- Enable Maintenance Mode
- Set a custom message to visitors:
```
"We're currently performing critical security maintenance on our website.
We'll be back online shortly. Thank you for your patience!
Expected completion: [time/date]
Questions? Contact us at [email]"
```
- Configure to allow admin login (so you can still access WordPress)
- Save settings
Method 2: Manual .htaccess Method (Advanced)
Add this code to your .htaccess file in the WordPress root directory:
# Maintenance mode - block all except admin
<FilesMatch "\.phpquot;>
Deny from all
</FilesMatch>
# Allow WordPress admin and specific IPs
<FilesMatch "wp-admin/admin-ajax\.php">
Allow from all
</FilesMatch>
# Optional: Allow specific IP addresses to access normally
Allow from YOUR.IP.ADDRESS.HERE
Then create an index.html file with your maintenance message:
<!DOCTYPE html>
<html>
<head>
<title>Maintenance Mode</title>
<style>
body { font-family: Arial, sans-serif; text-align: center; padding: 50px; }
h1 { color: #333; }
p { color: #666; font-size: 16px; }
</style>
</head>
<body>
<h1>🔒 Security Maintenance in Progress</h1>
<p>We're performing important security updates on our website.</p>
<p>We'll be back online shortly. Thank you for your patience!</p>
<p>Contact: [email protected]</p>
</body>
</html>
Why this matters:
- Prevents Google from crawling and indexing malicious content
- Keeps site visitors safe from malware distribution
- Gives you time to clean without worrying about real-time traffic
- Search engines understand maintenance mode and don't penalize your rankings
---
Part 4: Step-by-Step Malware Removal Process
Now that you've prepared and backed up, it's time to systematically remove malware. Follow these steps in order—each builds on the previous one. This is where the actual malware types you've detected get removed from your site.
Step 6: Reset Your Admin Password and Create a Secure New Account
This is crucial because attackers often create their own admin accounts or compromise existing ones. By creating a new account, you regain exclusive control.
Steps to secure your admin access:
In WordPress Admin (if you can still access it):
- Log in to WordPress with your current admin credentials
- Go to Users → All Users
- Click on your main admin account
- Scroll down to "Account Management"
- Enter a new, complex password:
- Minimum 16 characters
- Mix of uppercase and lowercase letters
- Include numbers and special symbols (!@#$%^&*)
- Use a password manager like 1Password or Bitwarden to generate it
- Example:
Tr0picalThund3r!Sec@2024#Unique - Save the changes
- Log out and log back in with the new password
- Verify you can access the dashboard
Create a completely new admin account:
- Go to Users → Add New
- Fill in:
- Username: Choose something unique (not "admin" or "administrator")
- Email: Your actual email address
- First Name/Last Name: Your real name
- Password: Generate a new complex password
- Role: Administrator
- Click "Add New User"
- Save this password in your password manager
Delete suspicious user accounts:
- Go to Users → All Users
- For each unknown or suspicious account:
- Click the username
- Scroll to bottom of edit page
- Select "Delete all content" or "Attribute to [your-new-admin]"
- Click "Delete"
- Verify only legitimate users remain
If you cannot access WordPress:
If WordPress is locked or heavily compromised, use phpMyAdmin to reset passwords:
-- Reset admin password to "newpassword123"
UPDATE wp_users SET user_pass=MD5('newpassword123') WHERE user_login='admin';
-- Verify the change
SELECT user_login, user_pass FROM wp_users;
Important notes:
- MD5 is for emergencies only—WordPress will rehash it on next login with proper encryption
- Keep track of the temporary password and change it immediately after logging in
- Never use weak passwords; attackers will brute-force them
- After cleanup, generate a password manager entry for each admin account
Step 7: Remove Suspicious Plugins and Themes
Malware frequently hides in outdated, abandoned, or malicious plugins. Removing them eliminates major attack vectors.
Complete plugin removal process:
- Deactivate all plugins except essential security plugins:
- Go to Plugins → Installed Plugins
- Sort by "Status" to see active plugins
- Deactivate each plugin by clicking "Deactivate"
- Keep only your security plugin active (Wordfence, Sucuri, etc.)
- Review each plugin carefully:
For each installed plugin, ask:
- Do I recognize this plugin?
- When did I last update it?
- Is it actively maintained?
- Does it have good ratings and reviews?
- Is it from a trusted developer?
- Delete suspicious plugins:
- Select checkbox next to suspicious plugins
- Click "Bulk Actions" → "Delete"
- Confirm deletion
- Reinstall legitimate plugins:
- Download fresh copies from WordPress.org
- Upload via Plugins → Add New → Upload Plugin
- Activate only the plugins you actually need
- Update all plugins to latest versions
Real-world red flag example:
I once found a plugin called "Image-Optimizer-Pro" that was actually a malware dropper. It had a legitimate-sounding name, zero reviews, and hadn't been updated in 3 years. When examined, it contained a backdoor script.
Complete theme removal process:
- Check installed themes:
- Go to Appearance → Themes
- Look at all installed themes, not just the active one
- Delete unnecessary themes:
- Hover over each theme
- Look for "Delete" option
- Delete any theme you don't recognize or don't use
- WordPress requires at least one active theme, so switch to a known-good theme first
- Reinstall active theme from official source:
- Download fresh copy of your theme from WordPress.org or the official developer
- Connect via SFTP and delete
/wp-content/themes/your-theme/directory completely - Upload the fresh theme files
- Verify it's still working correctly
- Disable unnecessary functionality:
- Go to Settings → General
- Check that only your desired theme is selected
- Verify correct Site Title and Tagline
- Save changes
Why fresh theme installation matters: If malware modified your theme files, even small edits could leave backdoors. A fresh installation ensures complete removal.
Step 8: Clean Your Database
Malware often injects content into your WordPress database, hiding spam links, malicious redirects, or hidden scripts. Database cleanup is one of the most critical steps because search engines index database content.
Understanding WordPress database structure:
The WordPress database contains several critical tables:
wp_posts- Your pages, posts, and post revisionswp_postmeta- Metadata associated with postswp_options- Site settings, theme options, plugin settingswp_users- User accounts and login datawp_usermeta- User metadata and capabilitieswp_comments- All comments and comment metadata
Malware can inject content into any of these tables.
Method 1: Using phpMyAdmin (Most Direct)
- Log in to your hosting control panel
- Open phpMyAdmin
- Select your WordPress database
- Search for suspicious content in
wp_poststable: - Click on
wp_poststable - Click "Search" tab
- Search for spam keywords: casino, viagra, pharmacy, betting, loan, etc.
- Review results carefully
- Inspect suspicious posts:
- Look at the post content
- Check post_status (should be 'publish', 'draft', 'pending', or 'private')
- Note the post IDs of suspicious content
Manual phpMyAdmin Queries to find malware:
-- Find posts with common spam keywords
SELECT ID, post_title, post_content FROM wp_posts
WHERE (post_content LIKE '%casino%'
OR post_content LIKE '%viagra%'
OR post_content LIKE '%pharmaceutical%'
OR post_content LIKE '%poker%'
OR post_content LIKE '%loan%'
OR post_content LIKE '%mortgage%')
AND post_status = 'publish';
-- Find posts with suspicious JavaScript
SELECT ID, post_title FROM wp_posts
WHERE post_content LIKE '%<script%'
OR post_content LIKE '%javascript:%'
OR post_content LIKE '%onerror=%'
OR post_content LIKE '%onclick=%';
-- Find hidden posts (possibly malicious)
SELECT ID, post_title, post_status FROM wp_posts
WHERE post_status NOT IN ('publish', 'draft', 'pending', 'private')
ORDER BY post_modified DESC;
-- Find posts with base64-encoded content (often malware)
SELECT ID, post_title, SUBSTRING(post_content, 1, 100) FROM wp_posts
WHERE post_content LIKE '%base64%decode%'
OR post_content REGEXP '^[A-Za-z0-9+/]{100,}={0,2}