Creating and managing a successful WordPress website involves many different tasks. You need to manage design tweaks, performance optimization, site security, and much more.
WordPress offers plugins for many tasks, but relying on them for every single tweak isn’t always the best approach.
In this article, we’ll share some helpful code snippets that can save you significant time on common tasks without needing another plugin.
Before we explore the best code snippets for WordPress, you might be wondering where and how exactly to put them on your website.
You might come across tutorials suggesting that you add snippets directly into your theme’s functions.php file. However, that’s not the safest approach. Making mistakes there can easily break your site. Also, you lose those customizations if your theme updates or changes.
Instead, the easiest and safest method is to use a snippet plugin. These plugins let you add multiple snippet types without touching any website files directly.
While many WordPress code snippet plugins are available, we recommend WPCodeBox. It’s designed to be a simple and safe snippet management plugin, perfect for both beginners and developers.
Here’s how simple it is to add a snippet:
Now that you know how easy it is to add a snippet, let’s look at some practical ones you can start using right away.
We’ll cover a range of common scenarios. These snippets will help you improve site performance, security, and customize the user experience.
The WordPress admin bar appears on the frontend of your site when a user is logged in. For many users, especially those who don’t need access to the WordPress dashboard (subscribers), this toolbar allows them to access pages they don’t need to visit.
It can also feel like visual clutter when you’re trying to view your website on the front end.
Instead of searching and installing another plugin just to hide the admin bar, you can use this snippet:
add_filter ('show_admin_bar', function ( $show_admin_bar ) {
if(!current_user_can ('manage_options' )) {
return false;
}
return $show_admin_bar;
});
Or you could also use one line of code:
add_filter( 'show_admin_bar', '__return_false' );
By default, your WordPress site will include a meta tag that shows which version of WordPress you are running, and attach the version number to the CSS and JS scripts that are enqueued.
Displaying your exact WordPress version can be a security risk as it makes it easier for hackers to identify if you are using an older version with known vulnerabilities that they could exploit.
This is a simple code snippet that provides a quick and easy security enhancement by hiding your WordPress version:
add_filter('the_generator', '__return_empty_string');
function remove_version_from_assets($src) {
$wp_version = get_bloginfo('version');
if (strpos($src, 'ver='. $wp_version) !== false) {
$src = remove_query_arg('ver', $src);
}
return $src;
}
add_filter('style_loader_src', 'remove_version_from_assets', 9999);
add_filter('script_loader_src', 'remove_version_from_assets', 9999);
WordPress has automatic updates for core files, plugins, and themes. While often helpful, automatic updates can sometimes cause unexpected issues or conflicts with your specific theme or plugin setup.
With hundreds of different plugins and themes available, it’s difficult to guarantee that every automatic update will be compatible with your site without breaking something.
This snippet gives you full control over updates by disabling the automatic update feature entirely. While you will need to perform updates manually, it significantly reduces the risk of your site breaking due to an update you weren’t prepared for.
add_filter('automatic_updater_disabled', '__return_true');
If you want more granular control, you can use these filters to disable updates selectively:
add_filter( 'auto_update_core', '__return_false' );
add_filter( 'auto_update_plugin', '__return_false' );
add_filter( 'auto_update_theme', '__return_false' );
Many WordPress users still prefer the writing experience offered by the Classic Editor over the newer block editor (Gutenberg).
Instead of installing the Classic Editor plugin, you can use the snippet below to set the Classic Editor as the default editor for all your posts and pages.
add_filter( 'use_block_editor_for_post', '__return_false', 10);
XML-RPC is a feature in WordPress that allows for remote communication, often used by mobile apps or desktop clients to publish content. However, this feature can sometimes be targeted by malicious bots for brute-force attacks.
When you disable XML-RPC, you stop a common source of such attacks. This saves you from the time-consuming hassle of cleaning up and recovering from potential breaches.
Here’s the same code snippet:
add_filter('xmlrpc_enabled','__return_false');
add _action('init', function() {
if(strpos($_SERVER['REQUEST_URI'],'xmlrpc.php') !== false) {
wp_redirect(home_url());
Exit;
}
});
Disabling REST API access for guests in WordPress is done for security and performance reasons. By restricting access, you can prevent unauthorized users from accessing potentially sensitive information or exploiting vulnerabilities in the API.
This also reduces the load on your server by limiting the requests that can be made by unauthenticated users. Here’s the code used in the video:
function disable_rest_api_for_guests($access) {
if(!is_user_logged_in()) {
return new WP_Error(
'rest_disabled',
__('The REST API is disabled for guests.'),
array ('status' => 403)
);
}
return $access;
add_filter('rest_authentication_errors','disable_rest_api_for_guests');
Out of the box, WordPress generates attachment pages that you don’t need.
You can change this behavior using a custom code solution tailored specifically for this. Here’s a video:
This snippet only works when there’s an attachment; it checks and applies a simple logic to define where to send any user who tries to access an attachment page. Here’s the snippet in question:
function redirect_attachments() {
if (!is_attachment()) {
return;
}
$attachment = get_post();
$parent_id = $attachment->post_parent;
$parent_post_status = get_post_status($parent_id);
$parent_permalink = get_permalink($parent_id);
$destination = home_url();
$http_status_code = 302;
if($parent_id && $parent_post_status !== 'trash') {
$destination = $parent_permalink;
$http_status_code = 301;
}
wp_safe_redirect($destination,$http_status_code);
exit;
}
add_action ('template_redirect', 'redirect_attachments', 1);
By default, the logo on your WordPress login page is the default WordPress logo..
Customizing this logo is a small but important detail for branding, especially if you manage sites for clients and want a white-labeled experience.
This snippet allows you to easily change the logo image that the login page uses:
function custom_login_logo() {
$logo_url = esc_url( wp_upload_dir()['baseurl'] . '/my-logo.svg');
$css = "#login h1 a {
background: url ('{$logo_url}') no-repeat center / contain;
width: auto;
max-width: 320px;
height: 80px;
}";
wp_add_inline_style( 'login', $css );
}
add_action( 'login_enqueue_scripts', 'custom_login_logo');
By default, WordPress disables SVG uploads to your site, but this can be easily changed by hooking into the allowed MIME types and including SVGs there. Here’s a video showing how this works:
We only enable this capability for admins to keep your site as secure as possible. This is the code in question:
function allow_svg_for_admins($mimes) {
if(current_user_can('manage_options')) {
$mimes['svg'] = 'image/svg+xml';
}
return $mimes;
}
add_filter('upload_mimes', 'allow_svg_for_admins');
Sometimes you need to work on your website behind the scenes, maybe updating plugins, or making design changes. You don’t want visitors to see a broken or incomplete site during this time.
This snippet provides a quick way to put your site into a simple “Under Maintenance” mode. It will display a custom message to regular visitors while still allowing logged-in administrators to see the site and work on it normally.
add_action('template_redirect', function() {
if( !current_user_can( 'manage_options' ) && !is_admin() ) {
status_header(503);
?>
<h1 style="font-family:system-ui;text-align:center;margin-top:100px;">
The site is currently in maintenance mode. Check back soon!
</h1>
<?php
exit;
}
});
The above snippet adds a simple maintenance message, which also tries to match your brand style. You can even design a custom maintenance page using page builders like Elementor or Divi, and replace the slug in the snippet below. Just remember to set the page template to ‘Full Canvas’ or similar to hide headers and footers.
/**
* Maintenance mode – redirect everybody except logged-in admins
* to the “Maintenance” page (slug: maintenance).
* Put this in mu-plugins or in your theme’s functions.php.
*/
add_action( 'template_redirect', function () {
/* 1. Let the back-end and logged-in admins through
------------------------------------------------ */
if ( is_admin() // wp-admin, ajax, cron …
|| is_user_logged_in() // any logged-in user
|| current_user_can( 'manage_options' ) ) {
return;
}
/* 2. If we’re already on the maintenance page, just serve it
and emit a 503 so Google knows the site is temporary down
------------------------------------------------------------ */
if ( is_page( 'maintenance' ) ) { // use the slug, not a raw URL
status_header( 503 );
header( 'Retry-After: 3600' ); // ask crawlers to come back in 1 h
return;
}
/* 3. Send everyone else to the maintenance page
--------------------------------------------- */
wp_safe_redirect( home_url( '/maintenance/' ), 307 ); // 307 = temporary
exit;
} );
That’s it. These are some of the snippets that can help you streamline your WordPress tasks, improve security, and user experience, all without needing extra plugins.
When you use the WPCodeBox plugin to manage your snippets, you can use the Functionality Plugin feature to run your custom code even if the main plugin is deactivated or removed.
It lets you save your code snippets to an entirely separate plugin file that is independent of the WPCodeBox plugin.
This is especially helpful for client handoffs. Your custom code remains active on their website, and clients cannot easily edit or accidentally break the code.
And whenever you make changes to your snippets inside the main plugin interface, they’re automatically updated inside the Functionality Plugin.
Here’s how it works with your snippets:
Let’s say you use WPCodeBox to add maintenance mode on your website (Snippet #10 from our list).
Creating and managing a successful WordPress website involves tackling many different tasks. This includes managing design tweaks, performance optimization, site security, and much more. As we’ve shown throughout this article, using simple code snippets offers a powerful way to save time on these common tasks without needing to install a separate plugin for every small function.
The snippets we shared cover a range of useful needs, from improving site performance and enhancing security to adding helpful customizations. You can easily add these snippets safely and easily to your website using a dedicated snippet plugin like WPCodeBox.
How safe is it to run custom code using WPCodeBox?
It’s much safer than editing theme or plugin files directly. WPCodeBox comes with built-in error detection that automatically disables any snippet if an error is found, preventing your site from breaking. This gives you peace of mind, especially when testing new or unfamiliar code. The error handling works in the background, so you can experiment without worrying about a white screen of death.
What code languages can I use in my snippets?
You can create code snippets in any of the following language: PHP, CSS, SCSS, LESS, JavaScript, HTML, JSON and Plain Text. This covers everything from back-end customizations (PHP) to front-end styling and scripting (CSS, JS). Plain Text is useful for notes or non-executable content that you want to keep alongside your active snippets.
Where are code snippets stored in WordPress?
When using WPcodeBox, your snippets are found in the following two database tables:
This approach keeps your custom code separate from theme and plugin files, making it easier to manage and backup. It also means your snippets remain intact even if you switch themes or update plugins.