WordPress Code Snippets are a smart alternative to installing heavy plugins that slow down your site and create security risks. Instead of adding a large plugin for a small feature, a few WordPress code snippets can improve performance, strengthen security, and streamline your workflow. Below is a curated list of 25 battle-tested WordPress code snippets that actually work.
Important: Read Before Using WordPress Code Snippets
1. The Golden Rule of Backups
Before editing any code, you must back up your website. If you make a typo in these files, your site could go offline.
- Action: Go to your hosting dashboard or use a backup plugin (like UpdraftPlus) and create a full backup of your Database and Files.
2. The Three Methods You Will Use
Throughout this guide, we will refer to three files. Here is how to access them for the steps below:
functions.php: Accessed via Dashboard > Appearance > Theme File Editor > functions.php. (Or via a plugin like WPCode).- ⚠️ Recommended: Always add this code to the child theme’s
functions.phpto prevent it from being overwritten during updates—if you haven’t created one yet, follow our guide on how to create a WordPress child theme safely
- ⚠️ Recommended: Always add this code to the child theme’s
wp-config.php: Accessed via your Hosting Control Panel > File Manager > public_html..htaccess: Accessed via your Hosting Control Panel > File Manager > public_html (Make sure “Show Hidden Files” is on).
Part 1: Security Hardening
1. Disable XML-RPC
- The Problem: XML-RPC is an outdated system that allows remote connections. It is the #1 target for brute-force attacks where bots try thousands of passwords to break into your site.
- The Solution: If you don’t use the WordPress mobile app or Jetpack, you should completely disable it to close this backdoor.
add_filter( 'xmlrpc_enabled', '__return_false' );
How to Paste (Step-by-Step):
- Log in to your WordPress Dashboard.
- Go to Appearance > Theme File Editor.
- On the right side, click Theme Functions (
functions.php). - Scroll to the very bottom of the file.
- Paste the code on a new line.
- Click Update File.
2. Hide WordPress Version Number
- The Problem: By default, your site’s source code creates a tag showing your specific WordPress version (e.g., 6.4.2). Hackers scan for this to find sites running old, vulnerable versions.
- The Solution: Remove this tag so attackers cannot easily see which version you are running.
remove_action('wp_head', 'wp_generator');
How to Paste (Step-by-Step):
- Go to Appearance > Theme File Editor.
- Open Theme Functions (
functions.php). - Paste the code at the bottom of the file.
- Click Update File.
3. Disable File Editing from Dashboard
- The Problem: If a hacker guesses your admin password, the first thing they do is go to the “Theme Editor” and inject malware directly into your site’s files.
- The Solution: This code removes the “Theme Editor” and “Plugin Editor” from the dashboard entirely, adding a critical layer of protection.
define( 'DISALLOW_FILE_EDIT', true );
How to Paste (Step-by-Step):
- Log in to your Hosting Control Panel (cPanel).
- Open File Manager.
- Go to the
public_htmlfolder. - Right-click
wp-config.phpand select Edit. - Find the line:
/* That's all, stop editing! Happy publishing. */ - Paste the code above that line.
- Click Save Changes.
4. Generic Login Error Messages
- The Problem: When a login fails, WordPress helpfully says “Unknown username” or “The password you entered is incorrect.” This tells hackers exactly which part they guessed right.
- The Solution: Change the error message to a generic “Something is wrong,” so hackers don’t know if the username exists or not.
function no_wordpress_errors(){
return 'Something is wrong! Please try again.';
}
add_filter( 'login_errors', 'no_wordpress_errors' );
How to Paste (Step-by-Step):
- Go to Appearance > Theme File Editor.
- Open
functions.php. - Paste the code at the bottom.
- Click Update File.
5. Add Security Headers (X-Frame & X-XSS)
- The Problem: Your site is vulnerable to “Clickjacking” (where other sites embed your site in a frame to trick users) and Cross-Site Scripting (XSS).
- The Solution: Add server-level headers that tell browsers to block these specific types of attacks.
<IfModule mod_headers.c>
Header set X-XSS-Protection "1; mode=block"
Header set X-Frame-Options "SAMEORIGIN"
Header set X-Content-Type-Options "nosniff"
Header set Referrer-Policy "strict-origin-when-cross-origin"
</IfModule>
How to Paste (Step-by-Step):
- Log in to your Hosting File Manager.
- Locate
.htaccessinpublic_html. (If missing, click Settings > Show Hidden Files). - Right-click and Edit.
- Paste the code at the very top of the file.
- Click Save. Check your site immediately to ensure it loads.
Part 2: Performance & Speed
6. Disable Emojis Script
- The Problem: WordPress loads a heavy JavaScript file on every single page load just to render emojis (😊) on very old browsers. Modern devices don’t need this.
- The Solution: Remove this script to save roughly ~50KB of page weight and reduce HTTP requests.
function disable_emojis() {
remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
remove_action( 'wp_print_styles', 'print_emoji_styles' );
remove_action( 'admin_print_styles', 'print_emoji_styles' );
remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );
}
add_action( 'init', 'disable_emojis' );
How to Paste (Step-by-Step):
- Go to Appearance > Theme File Editor >
functions.php. - Paste the code at the bottom.
- Click Update File.
7. Limit Post Revisions
- The Problem: Every time you click “Save Draft,” WordPress creates a new copy of your post in the database. Over years, this creates thousands of useless rows that slow down your site.
- The Solution: Limit WordPress to keep only the last 3 revisions, keeping your database lean.
define( 'WP_POST_REVISIONS', 3 );
How to Paste (Step-by-Step):
- Open Hosting File Manager.
- Edit
wp-config.php. - Paste the code above the line
/* That's all, stop editing! */. - Click Save.
8. Increase PHP Memory Limit
- The Problem: You see the “Allowed memory size exhausted” error. This happens when a heavy theme or plugin (like Elementor) needs more power than default.
- The Solution: Force WordPress to allow up to 256MB of memory usage.
define( 'WP_MEMORY_LIMIT', '256M' );
How to Paste (Step-by-Step):
- Open Hosting File Manager.
- Edit
wp-config.php. - Paste the code inside.
- Click Save.
9. Disable Self-Pingbacks
- The Problem: When you link to your own article in a new post, WordPress creates a “Pingback” notification in your comments section. It’s annoying clutter.
- The Solution: Stop WordPress from notifying itself about internal links.
function no_self_ping( &$links ) {
$home = get_option( 'home' );
foreach ( $links as $l => $link )
if ( 0 === strpos( $link, $home ) )
unset($links[$l]);
}
add_action( 'pre_ping', 'no_self_ping' );
How to Paste (Step-by-Step):
- Go to Appearance > Theme File Editor >
functions.php. - Paste the code at the bottom.
- Click Update File.
10. Disable RSS Feeds
- The Problem: If you run a standard business website (not a blog), you don’t need RSS feeds. Scrapers use these feeds to automatically steal your content.
- The Solution: Disable the feed entirely and redirect anyone trying to access it back to your homepage.
function disable_feed() {
wp_die( 'No feed available, please visit the <a href="'. get_bloginfo('url') .'">homepage</a>!' );
}
add_action('do_feed', 'disable_feed', 1);
add_action('do_feed_rdf', 'disable_feed', 1);
add_action('do_feed_rss', 'disable_feed', 1);
add_action('do_feed_rss2', 'disable_feed', 1);
add_action('do_feed_atom', 'disable_feed', 1);
How to Paste (Step-by-Step):
- Go to Appearance > Theme File Editor >
functions.php. - Paste the code at the bottom.
- Click Update File.
Part 3: Admin Dashboard Customization
11. Custom Login Logo
- The Problem: The login page displays the WordPress “W” logo by default. If you are building a site for a client, this looks generic.
- The Solution: Replace the default logo with your own custom brand logo.
function my_login_logo() { ?>
<style type="text/css">
#login h1 a, .login h1 a {
background-image: url(<?php echo get_stylesheet_directory_uri(); ?>/images/logo.png);
height:65px;
width:320px;
background-size: contain;
background-repeat: no-repeat;
}
</style>
<?php }
add_action( 'login_enqueue_scripts', 'my_login_logo' );
How to Paste (Step-by-Step):
- Upload your logo (name it
logo.png) to your hosting folder:/wp-content/themes/your-theme/images/. - Go to Appearance > Theme File Editor >
functions.php. - Paste the code.
- Click Update File.
12. Change Login Logo URL
- The Problem: Even if you change the image, clicking the logo on the login screen still takes you to
WordPress.org. - The Solution: Rewrite the link so clicking the logo takes the user to your site’s homepage.
function my_login_logo_url() {
return home_url();
}
add_filter( 'login_headerurl', 'my_login_logo_url' );
How to Paste (Step-by-Step):
- Go to Appearance > Theme File Editor >
functions.php. - Paste the code at the bottom.
- Click Update File.
13. Remove Admin Bar for Non-Admins
- The Problem: By default, WordPress shows a black toolbar at the top of the website for anyone who is logged in. This looks confusing for regular customers.
- The Solution: This code checks the user’s role. If they are not an Administrator, it hides the toolbar.
add_action('after_setup_theme', 'remove_admin_bar');
function remove_admin_bar() {
if (!current_user_can('administrator') && !is_admin()) {
show_admin_bar(false);
}
}
How to Paste (Step-by-Step):
- Go to Appearance > Theme File Editor >
functions.php. - Paste the code.
- Click Update File.
14. Change “Howdy, User” Greeting
- The Problem: In the top right corner, WordPress greets you with “Howdy.” Many clients feel this sounds too casual for a corporate environment.
- The Solution: This snippet filters that text and changes it to a more professional “Welcome”.
function replace_howdy( $wp_admin_bar ) {
$my_account=$wp_admin_bar->get_node('my-account');
$newtitle = str_replace( 'Howdy,', 'Welcome,', $my_account->title );
$wp_admin_bar->add_node( array(
'id' => 'my-account',
'title' => $newtitle,
) );
}
add_filter( 'admin_bar_menu', 'replace_howdy',25 );
How to Paste (Step-by-Step):
- Go to Appearance > Theme File Editor >
functions.php. - Paste the code.
- Click Update File.
15. Allow SVG Uploads
- The Problem: SVG files are crisp and small, but WordPress blocks them for security reasons.
- The Solution: This snippet whitelists the SVG file type, allowing you to upload logos and icons directly to the Media Library.
function add_file_types_to_uploads($file_types){
$new_filetypes = array();
$new_filetypes['svg'] = 'image/svg+xml';
$file_types = array_merge($file_types, $new_filetypes );
return $file_types;
}
add_filter('upload_mimes', 'add_file_types_to_uploads');
How to Paste (Step-by-Step):
- Go to Appearance > Theme File Editor >
functions.php. - Paste the code.
- Click Update File.
- Test by uploading an
.svgfile in Media > Add New.
Part 4: Frontend & Content Snippets
16. Auto-Updating Copyright Year
- The Problem: Every January, site owners must manually edit their footer to update the year (e.g., “Copyright 2024”). It’s easy to forget.
- The Solution: Creates a shortcode
[year]that automatically displays the current server year.
function year_shortcode() {
$year = date('Y');
return $year;
}
add_shortcode('year', 'year_shortcode');
How to Paste (Step-by-Step):
- Go to
functions.phpand paste the code. - Click Update File.
- Go to Appearance > Widgets.
- Drag a Text Widget to your footer and type:
© [year] My Company.
17. Enable Shortcodes in Widgets
- The Problem: Shortcodes (like the one above) usually don’t work if you paste them into a standard “Text Widget” in your sidebar.
- The Solution: This filter tells WordPress to process shortcodes inside widgets, not just in post content.
add_filter('widget_text', 'do_shortcode');
How to Paste (Step-by-Step):
- Go to Appearance > Theme File Editor >
functions.php. - Paste the code.
- Click Update File.
18. Remove “Website” Field from Comments
- The Problem: Spambots love comment forms because they can leave a link to their malicious site in the “Website” field.
- The Solution: Completely removes the “Website” input box from the comment form, drastically reducing spam.
function remove_website_field($fields) {
if(isset($fields['url']))
unset($fields['url']);
return $fields;
}
add_filter('comment_form_default_fields', 'remove_website_field');
How to Paste (Step-by-Step):
- Go to Appearance > Theme File Editor >
functions.php. - Paste the code.
- Click Update File.
19. Estimated Reading Time
- The Problem: Visitors are more likely to read an article if they know it’s short. Most themes don’t display “Reading Time.”
- The Solution: Adds a
[reading_time]shortcode that calculates the word count and displays “Reading Time: X mins.”
function reading_time() {
$content = get_post_field( 'post_content', get_the_ID() );
$word_count = str_word_count( strip_tags( $content ) );
$readingtime = ceil($word_count / 200);
if ($readingtime == 1) { $timer = " minute"; } else { $timer = " minutes"; }
$totalreadingtime = $readingtime . $timer;
return "Reading Time: " . $totalreadingtime;
}
add_shortcode('reading_time', 'reading_time');
How to Paste (Step-by-Step):
- Go to
functions.phpand paste the code. - Click Update File.
- Open any blog post and type
[reading_time]where you want the timer to appear.
20. Disable Image Link Defaults
- The Problem: When you insert an image, WordPress often links it to the “Media File” by default. If a user clicks the image, they are taken to a blank page with just the image, which is bad UX.
- The Solution: Sets the default image link behavior to “None.”
function wpb_imagelink_setup() {
$image_set = get_option( 'image_default_link_type' );
if ($image_set !== 'none') {
update_option('image_default_link_type', 'none');
}
}
add_action('admin_init', 'wpb_imagelink_setup', 10);
How to Paste (Step-by-Step):
- Go to Appearance > Theme File Editor >
functions.php. - Paste the code.
- Click Update File.
Part 5: Maintenance & Utility
21. Maintenance Mode (No Plugin)
- The Problem: When fixing your site, you don’t want visitors seeing a broken layout. Maintenance plugins are often heavy.
- The Solution: This code locks the front end for visitors (showing a message) but allows logged-in admins to see the site normally.
function wp_maintenance_mode() {
if (!current_user_can('edit_themes') || !is_user_logged_in()) {
wp_die('<h1>Under Maintenance</h1><br />We are performing scheduled maintenance. We will be back online shortly!');
}
}
add_action('get_header', 'wp_maintenance_mode');
How to Paste (Step-by-Step):
- Go to
functions.php. - Paste the code and Click Update.
- Note: To turn it off, you must delete this code or add
//in front of each line.
22. Disable Admin Email Checks
- The Problem: WordPress interrupts your workflow every few months with a full-screen “Is this email still correct?” prompt.
- The Solution: Disables this check entirely so you are never interrupted again.
add_filter( 'admin_email_check_interval', '__return_false' );
How to Paste (Step-by-Step):
- Go to Appearance > Theme File Editor >
functions.php. - Paste the code.
- Click Update File.
23. Redirect 404 Errors to Homepage
- The Problem: If a user clicks a broken link, they see an ugly “404 Error” page, and they usually leave the site immediately.
- The Solution: Automatically redirects any 404 error back to the homepage, keeping the user on your site.
function all_404_redirect_to_homepage() {
if(is_404()){
wp_redirect(home_url());
exit;
}
}
add_action('template_redirect', 'all_404_redirect_to_homepage');
How to Paste (Step-by-Step):
- Go to Appearance > Theme File Editor >
functions.php. - Paste the code.
- Click Update File.
24. Force Minimum Content Length
- The Problem: If you have multiple authors, they might publish “thin content” (short 50-word posts) that hurts your SEO.
- The Solution: Prevents the “Publish” button from working if the post is under 100 words.
function force_min_words($content) {
global $post;
$num = 100; // Minimum words required
$content = $post->post_content;
if (str_word_count($content) < $num) {
wp_die( __('Error: Your post is too short. Please add more content.') );
}
}
add_action('publish_post', 'force_min_words');
How to Paste (Step-by-Step):
- Go to Appearance > Theme File Editor >
functions.php. - Paste the code.
- Click Update File.
25. Enable WebP Uploads
- The Problem: WebP images are superior for speed, but older versions of WordPress or certain server configs block them.
- The Solution: Explicitly allows the
.webpMIME type in the uploader.
function webp_upload_mimes($existing_mimes) {
$existing_mimes['webp'] = 'image/webp';
return $existing_mimes;
}
add_filter('mime_types', 'webp_upload_mimes');
How to Paste (Step-by-Step):
- Go to Appearance > Theme File Editor >
functions.php. - Paste the code.
- Click Update File.
- You can now upload
.webpfiles in your Media Library.
