Essential WordPress PHP functions for security

Estimated Reading Time: 4 min

Rate this post

Here are some essential WordPress PHP functions for security to help protect your website from vulnerabilities, attacks, and unauthorized access.


1. Disable File Editing in the Admin Panel

Hackers can exploit the Theme & Plugin Editor to insert malicious code. Disable it using:

define('DISALLOW_FILE_EDIT', true);

Add this to your wp-config.php file.


2. Disable XML-RPC to Prevent DDoS Attacks

XML-RPC is often exploited for brute force and DDoS attacks. Disable it using:

add_filter('xmlrpc_enabled', '__return_false');

For better security, disable access completely via .htaccess:

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

3. Limit Login Attempts to Prevent Brute Force Attacks

function limit_login_attempts($user, $username, $password) {
    if (get_transient('login_attempts_' . $username) >= 5) {
        return new WP_Error('too_many_attempts', __('Too many failed login attempts. Please try again later.'));
    }
    
    $user = get_user_by('login', $username);
    if (!$user || !wp_check_password($password, $user->user_pass, $user->ID)) {
        set_transient('login_attempts_' . $username, (get_transient('login_attempts_' . $username) ?: 0) + 1, 15 * MINUTE_IN_SECONDS);
    }
    return $user;
}
add_filter('wp_authenticate_user', 'limit_login_attempts', 10, 3);

This function limits login attempts and locks out users after five failed attempts.


4. Hide WordPress Version

Attackers can use the WordPress version to target known vulnerabilities. Hide it using:

remove_action('wp_head', 'wp_generator');
function remove_version_strings($src) {
    return remove_query_arg('ver', $src);
}
add_filter('script_loader_src', 'remove_version_strings');
add_filter('style_loader_src', 'remove_version_strings');

5. Disable Directory Browsing

Prevent users from accessing directories by adding this to your .htaccess file:

Options -Indexes

6. Force Strong Passwords for Users

function enforce_strong_passwords($errors, $sanitized_user_login, $user_email) {
    if (!preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/', $_POST['pass1'])) {
        $errors->add('weak_password', __('Your password must be at least 8 characters long and include uppercase, lowercase, a number, and a special character.'));
    }
    return $errors;
}
add_filter('registration_errors', 'enforce_strong_passwords', 10, 3);

7. Auto-Logout Inactive Users

function auto_logout_idle_users() {
    if (is_user_logged_in() && (time() - get_user_meta(get_current_user_id(), 'last_activity', true)) > 1800) {
        wp_logout();
        wp_redirect(home_url());
        exit();
    }
    update_user_meta(get_current_user_id(), 'last_activity', time());
}
add_action('init', 'auto_logout_idle_users');

This function logs out inactive users after 30 minutes of inactivity.


8. Disable User Enumeration

Hackers often enumerate users to find admin usernames. Disable it using:

if (!is_admin()) {
    add_action('init', function() {
        if (isset($_REQUEST['author'])) {
            wp_redirect(home_url());
            exit;
        }
    });
}

9. Restrict Access to the WordPress Admin Panel

function restrict_admin_panel() {
    if (!current_user_can('administrator') && is_admin()) {
        wp_redirect(home_url());
        exit;
    }
}
add_action('init', 'restrict_admin_panel');

This prevents non-admin users from accessing the WordPress admin area.


10. Change the Default WordPress Login URL

Using a plugin like WPS Hide Login is the easiest way to change your login URL. If you want a manual solution, modify .htaccess to block access to wp-login.php for unknown IPs:

<Files wp-login.php>
    Order Deny,Allow
    Deny from all
    Allow from 123.45.67.89
</Files>

Replace 123.45.67.89 with your IP.


11. Secure wp-config.php

Make wp-config.php inaccessible by adding this to .htaccess:

<Files wp-config.php>
    Order Allow,Deny
    Deny from all
</Files>

12. Disable PHP Execution in Uploads and Plugin Directory

Prevent attackers from running malicious scripts by creating an .htaccess file in /wp-content/uploads/ and /wp-content/plugins/ with:

<FilesMatch "\.(php|php5|php7|php8)$">
    Order Deny,Allow
    Deny from all
</FilesMatch>

13. Enable Two-Factor Authentication (2FA)

You can enforce Two-Factor Authentication for extra security using a plugin like Google Authenticator – Two Factor Authentication or WP 2FA.


14. Restrict REST API Access

By default, the REST API can expose user data. Restrict it using:

function disable_rest_api_for_non_logged_users($result) {
    if (!is_user_logged_in()) {
        return new WP_Error('rest_forbidden', __('REST API access restricted.'), array('status' => 403));
    }
    return $result;
}
add_filter('rest_authentication_errors', 'disable_rest_api_for_non_logged_users');

15. Scan for Malware Regularly

Use security plugins like Wordfence, Sucuri, or MalCare to scan your website for malware and vulnerabilities.


Final Thoughts

These WordPress security functions help safeguard your site against common vulnerabilities. Combine these with best practices like regular updates, backups, and using strong passwords for optimal security.

Would you like additional tips or help implementing these functions? 🚀

Photo of author

Flora

Essential WordPress PHP functions for security

Published

I am Flora, the publisher and founder of *Be-Smart*, a platform dedicated to sharing insights and inspiration for living a fulfilling life. With a strong background in the web, my goal is to empower people to genuinely recognize and celebrate admirable actions big or small in themselves and others.

Leave a Comment