Boost Your WordPress Security with This Custom PHP Code

⏲️ Estimated reading time: 5 min

Below is a draft for a WordPress blog post that explains your security enhancement code. You can copy this content into a new post in your WordPress admin dashboard under Posts > Add New, then format it using the block editor (e.g., add headings, code blocks, etc.). I’ve written it in a user-friendly tone with some SEO-friendly phrasing, assuming it’s for a general WordPress audience.


WordPress powers millions of websites, making it a prime target for hackers. While plugins like Wordfence or iThemes Security are fantastic, sometimes you want a lightweight, custom solution tailored to your needs. In this post, I’ll share a powerful PHP script that enhances WordPress security covering everything from login protection to security headers. Whether you’re a developer or a site owner, this code is easy to implement and highly effective.

What This Code Does

This custom security script, which I’ve dubbed “Blade Security Enhancements,” adds several layers of protection to your WordPress site:

  • Hides WordPress Version: Prevents attackers from identifying your WP version.
  • Disables XML-RPC: Blocks a common attack vector used in brute force attempts.
  • Limits Login Attempts: Locks out users after 3 failed attempts for 15 minutes.
  • Adds Security Headers: Protects against clickjacking, XSS, and more.
  • Prevents User Enumeration: Stops hackers from listing users via the REST API.
  • Disables File Editing: Locks down the admin dashboard’s code editor.

Ready to secure your site? Let’s dive into the code and setup.

The Custom PHP Code

Here’s the full script you can add to your WordPress site:

<?php
// Custom Security Enhancements for WordPress
function blade_secure_wordpress() {
    remove_action('wp_head', 'wp_generator');
    add_filter('xmlrpc_enabled', '__return_false');
    remove_action('wp_head', 'rsd_link');
    add_filter('login_errors', function($error) {
        if (isset($_GET['error']) && $_GET['error'] === 'locked_out') {
            return 'Too many attempts. Locked out for 15 minutes.';
        }
        return 'Invalid login credentials.';
    });

    add_action('send_headers', function() {
        header('X-Frame-Options: SAMEORIGIN');
        header('X-Content-Type-Options: nosniff');
        header('X-XSS-Protection: 1; mode=block');
        if (!is_admin()) {
            header('Strict-Transport-Security: max-age=31536000; includeSubDomains; preload');
            header('Referrer-Policy: no-referrer-when-downgrade');
            header("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; object-src 'none';");
        }
    });

    add_filter('rest_endpoints', function($endpoints) {
        unset($endpoints['/wp/v2/users'], $endpoints['/wp/v2/users/(?P<id>[\d]+)']);
        return $endpoints;
    });
}
add_action('init', 'blade_secure_wordpress');

// Define in wp-config.php: define('DISALLOW_FILE_EDIT', true);

function blade_limit_login_attempts($username) {
    $max_attempts = 3;
    $lockout_time = 15 * 60;
    $ip = $_SERVER['REMOTE_ADDR'];
    $attempt_key = 'blade_login_attempts_' . md5($ip . $username);
    $lockout_key = 'blade_login_lockout_' . md5($ip . $username);

    if (get_transient($lockout_key)) {
        wp_redirect(wp_login_url() . '?error=locked_out');
        exit;
    }

    $attempts = (int) get_transient($attempt_key);
    $attempts++;

    if ($attempts >= $max_attempts) {
        set_transient($lockout_key, true, $lockout_time);
        delete_transient($attempt_key);
        wp_redirect(wp_login_url() . '?error=locked_out');
        exit;
    } else {
        set_transient($attempt_key, $attempts, $lockout_time);
    }
}
add_action('wp_login_failed', 'blade_limit_login_attempts');

function blade_reset_attempts($user_login) {
    $ip = $_SERVER['REMOTE_ADDR'];
    $attempt_key = 'blade_login_attempts_' . md5($ip . $user_login);
    delete_transient($attempt_key);
}
add_action('wp_login', 'blade_reset_attempts');
Boost Your WordPress Security with Custom PHP Code

How to Install Custom PHP Code

Follow these steps to add this security boost to your WordPress site:

  1. Option 1: Add to Your Theme
  • Open your theme’s functions.php file (found in wp-content/themes/your-theme/).
  • Paste the code at the bottom.
  • Save and upload.
  1. Option 2: Create a Custom Plugin (Recommended)
  • Go to wp-content/plugins/, create a folder called blade-security.
  • Add a file named blade-security.php with this header: “`php
    • Plugin Name: Blade Security Enhancements
    • Description: Custom security tweaks for WordPress.
    • Version: 1.0
    • Author: [Your Name]
      */
      “`
  • Paste the code below the header, save, and activate it from the WordPress admin dashboard.
  1. Set DISALLOW_FILE_EDIT
  • Edit wp-config.php in your WordPress root directory.
  • Add define('DISALLOW_FILE_EDIT', true); before /* That's all, stop editing! */.
  1. Test It
  • Check your site’s source code (Ctrl+U) to confirm the WP version is hidden.
  • Try logging in with wrong credentials 3 times to test the lockout.
  • Visit yoursite.com/xmlrpc.php it should say XML-RPC is disabled.

Customization Tips

  • Login Limits: Change $max_attempts or $lockout_time (in seconds) to fit your needs.
  • CSP Headers: If your site uses external scripts (e.g., Google Fonts), update the Content-Security-Policy line with allowed domains.
  • HTTPS: Ensure your site uses SSL for Strict-Transport-Security to work.

Why This Matters

Hackers exploit weak login systems, outdated software info, and missing headers. This script tackles those vulnerabilities head-on, giving you peace of mind without the bloat of a full security plugin. It’s lightweight, customizable, and perfect for DIY security enthusiasts.


This code is a great starting point, but security is an ongoing process. Combine it with strong passwords, two-factor authentication, and regular backups for maximum protection. Have questions or need tweaks? Drop a comment below I’d love to help!


📩 Do you have questions or suggestions? Leave a comment or contact us!

🏷️ Tags: Custom Plugin, Cybersecurity, login security, PHP Code, REST API Protection, Security Headers, Website Protection, WordPress Security, WordPress Tweaks, XML-RPC Disable
📢 Hashtags: #CustomPlugin, #Cybersecurity, #loginsecurity, #PHPCode, #RESTAPIProtection, #SecurityHeaders, #WebsiteProtection, #WordPressSecurity, #WordPressTweaks, #XML-RPCDisable

Report an issue (max 5 words):

We store the message, post link, time, and IP (for abuse prevention). No account required.

Want to support us? Let friends in on the secret and share your favorite post!

1 online now

Live Referrers

Photo of author

Flo

Boost Your WordPress Security with This Custom PHP Code

Published

Update

Welcome to HelpZone.blog, your go-to hub for expert insights, practical tips, and in-depth guides across technology, lifestyle, business, entertainment, and more! Our team of passionate writers and industry experts is dedicated to bringing you the latest trends, how-to tutorials, and valuable advice to enhance your daily life. Whether you're exploring WordPress tricks, gaming insights, travel hacks, or investment strategies, HelpZone is here to empower you with knowledge. Stay informed, stay inspired because learning never stops! 🚀

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.