WordPress is powerful out of the box—but a few smart additions to your functions.php
file can dramatically improve your site’s security and data hygiene.
Here are some practical, production-safe snippets I’ve used to protect logins, disable unnecessary access, and prevent information leakage—without a plugin in sight.
🔒 1. Disable REST API for Non-Logged-in Users
add_filter('rest_authentication_errors', function($result) {
if (!is_user_logged_in()) {
return new WP_Error('rest_forbidden', 'REST API restricted.', ['status' => 401]);
}
return $result;
});
Why use it: Blocks anonymous access to your site’s JSON data, which can be scraped or misused.
When to use it: For sites that don’t need public REST access—especially blogs or brochure sites.
👤 2. Block User Enumeration via URL
add_action('init', function() {
if (!is_admin() && isset($_GET['author'])) {
wp_redirect(home_url());
exit;
}
});
Why use it: Prevents bots from accessing ?author=1
and revealing usernames.
When to use it: Always, unless you rely on author archives and publicly visible usernames.
📨 3. Obscure Login Errors
add_filter('login_errors', fn() => 'Login failed.');
Why use it: Prevents WordPress from telling attackers whether the username or password was wrong.
When to use it: On every site, unless you’re debugging login issues and want verbose errors (briefly).
🔌 4. Disable XML-RPC
add_filter('xmlrpc_enabled', '__return_false');
Why use it: XML-RPC is a common vector for brute force and DDoS attacks. Most modern sites don’t need it.
When to use it: Unless you’re using Jetpack or a mobile publishing app—disable it.
🔐 5. Enforce Strong Passwords by Role
add_action('user_profile_update_errors', function($errors, $update, $user) {
if (in_array('administrator', $user->roles) && strlen($_POST['pass1']) < 12) {
$errors->add('pass_strength', 'Admins must use at least 12-character passwords.');
}
}, 10, 3);
Why use it: Forces stronger passwords for sensitive roles like Admin or Editor.
When to use it: On any site where admins are manually created or updated via the dashboard.
📉 6. Remove WordPress Version from Head
remove_action('wp_head', 'wp_generator');
Why use it: Removes the version meta tag from your source code to reduce targeted exploits.
When to use it: Always—unless you’re debugging compatibility or cache issues.
📁 7. Protect wp-config.php via .htaccess (Apache Only)
<Files wp-config.php>
order allow,deny
deny from all
</Files>
Why use it: Blocks direct access to your most sensitive core file if server config allows it.
When to use it: On Apache servers with .htaccess support. Doesn’t apply to NGINX or LiteSpeed setups.
✅ Final Thoughts
These aren’t hacks—they’re best practices. Each one gives your site a little more resilience and peace of mind.
If you’re building client sites or managing installs at scale, these lightweight defenses can make a real difference—no plugins required.
Next up in the Smart Snippets series: Part 4 – Smart Content Logic
Leave a Reply