Useful Code Snippets for Your WordPress Functions File

This post may contain affiliate links. If you purchase something through one of those links then we'll get a small commission.

WordPress is a fantastic content management system (CMS) for many businesses, but sometimes it doesn't work quite the way you want it to.

Extensive customisations to the design or functionality of a WordPress website will require professional web design and development expertise, but changing how WordPress works can, for the most part, be achieved by making simple tweaks to your theme's functions file.

Want to change the WordPress admin footer text? Want to disable post revisions? Need to exclude certain blog post categories from appearing in your search results? You can do all of that by simply copying and pasting a code snippet into your functions.php file.

To get you started, I've put together a quick step-by-step guide to editing this important core file.

See also: How to Change the Width of the Gutenberg Editor

Editing the functions file

1. Open your FTP client (for the purpose of this quick tutorial I'll be using FileZilla) and enter your FTP host, username, password and port number. Check with your web host if you're not sure what to enter in these fields.

FileZilla login form
FileZilla login form

2. After you've entered your details, click the "Quick connect" button.

FileZilla quick connect button
FileZilla quick connect button

3. Once you've logged into your site, use your FTP client to navigate to your theme folder. Typically this is public_html/wp-content/themes/[your-theme]/.

WordPress theme folder
WordPress theme folder

4. Next, right-click your theme's functions.php file and click "Download" to download it to your computer.

Download the WordPress functions file
Download the WordPress functions file

5. Then open the file in your favourite code editor (I use Sublime Text, but Visual Studio Code and Atom are also great choices) and add any of the awesome snippets below.

6. Once you've made your changes, save the functions file and then open up your FTP client again. Browse to your WordPress theme folder (where the functions.php file is located), right-click the functions file that's on your computer (that you've just edited) and click "Upload". Depending on your FTP client preferences, you may have to confirm that you want to overwrite the file that's on your server.

Upload the WordPress functions file
Upload the WordPress functions file

Child themes and backups

Each WordPress theme comes with its own functions.php file. If you're going to make extensive modifications to yours, I strongly advise you to set up a child theme so your changes don't disappear when you update your theme.

It's also a very good idea to make a backup of your site before editing your theme, just in case something goes wrong and you need to roll back your changes.

Functions file code snippets

Now you know how to edit the functions file, let's get pimping your website with these useful code snippets for your WordPress functions file!

Add alt text to Gravatar images

Anyone who knows anything about search engine optimisation (SEO) will tell you that adding descriptive alt text to your images is a low-hanging fruit that's relatively quick and easy to fix.

The primary purpose of image alt text is to describe images to people who can't see them, but it can also directly benefit a site's SEO as well. Well-optimised images typically appear higher in image search results, potentially bringing more organic traffic to a site.

For some inexplicable reason, WordPress doesn't include default alt text when it grabs an author image from the Gravatar server. The code snippet below fixes that. Simply copy and paste it into your theme's functions file, and the alt text "Gravatar for [author name]" will be automagically added to author Gravatars.

// Add alt text to Gravatar images
function megademic_gravatar_alt( $text ) {
    $alt = get_the_author_meta( 'display_name' );
    $text = str_replace( 'alt=\'\'', 'alt=\'Avatar for '.$alt.'\' title=\'Gravatar for '.$alt.'\'', $text );
    return $text;
}
add_filter( 'get_avatar', 'megademic_gravatar_alt' );

There are times when being able to edit the default text that appears at the bottom of the WordPress admin dashboard would be very useful.

Maybe you built the website for a client and want to include a web design credit. Perhaps you want to include a link to a support resource for clients or internal staff. Or it could be that you want to include an inspirational quote to get your creative juices flowing.

Whatever the reason, changing it is simply a matter of inserting the code snippet below into your theme's functions.php file. Then all you have to do is replace our content with your own.

// Change the WordPress admin dashboard footer
function megademic_change_admin_footer () {
    echo '<p>Created with <a href="https://www.wordpress.org" target="_blank">WordPress</a> | Website design by <a href="https://www.megademic.com" target="_blank">Megademic</a></p>';
}
add_filter( 'admin_footer_text', 'megademic_change_admin_footer' );

Add 'odd' and 'even' classes to WordPress posts

Tables and spreadsheets with alternating row colours are generally easier to read and interpret, as these "zebra stripes" provide the eye with a reference point when scanning a row horizontally.

Employing a similar web design tactic on blog archive pages can help visitors to quickly and easily identify one blog post from the next. They can also help transform boring post lists into something more aesthetically pleasing.

Inserting the code snippet below into your functions file will add "odd" and "even" classes to odd and even-numbered blog posts respectively. Posts one, three and five will be given the "odd" class, while posts two, four and six will be given the "even" class.

// Add "odd" and "even" classes to WordPress posts
function megademic_odd_even_post_class ( $classes ) {
   global $current_class;
   $classes[] = $current_class;
   $current_class = ( $current_class == 'odd' ) ? 'even' : 'odd';
   return $classes;
}
add_filter ( 'post_class' , 'megademic_odd_even_post_class' );
global $current_class;
$current_class = 'odd';

Once each post in your list has been given an "odd" or "even" class, the final step is to style them using CSS. You can add custom styles to your child theme's stylesheet, or use a plugin such as Simple Custom CSS or the amazing WPCodeBox to override plugin and theme styles.

The following CSS can be added to your stylesheet to create visual separation between blog posts.

/* Odd and even classes */
.odd { background-color: #f8f7fd; }

.even { background-color: #eae7f9; }

Disable WordPress' image compression feature

Many people don't realise that WordPress automatically compresses uploaded JPG images by up to 90%. If these images are further compressed with an image optimisation plugin like ShortPixel or WP Smush, the drop in image quality often results in blurry, pixelated images.

We've put together a detailed tutorial on how to stop WordPress compressing JPG images, which shows you how to disable the built-in image compression feature with the functions file or a separate plugin.

Using a plugin for such a simple task is overkill; I recommend adding the code snippet below to your theme's functions.php file instead.

// Disable WordPress image compression
add_filter( 'wp_editor_set_quality', function( $arg ) {
    return 100;
});

Disable XML-RPC

XML-RPC is a system that allows remote updates to WordPress from external services and desktop applications. However, this convenience comes at a price: reduced security.

Over the last few years, XML-RPC has become an increasingly frequent target for brute force attacks, simply because it's yet another path into WordPress.

If you don't use third-party applications to update your WordPress website, it makes sense to disable XML-RPC completely. There's no configuration option to do that, but adding the snippet below to your functions file will turn off XML-RPC and make your site a little more secure.

// Disable XML-RPC
add_filter( 'xmlrpc_enabled', '__return_false' );

Remove WordPress version number

Anyone interested in securing their website will no doubt have been told at some point to "hide the WordPress version number". Like changing the database table prefix from the default wp_, this tactic is known as "security through obscurity".

Whilst certainly not a foolproof way to deter even a semi-determined hacker on it's own, employing "security through obscurity" techniques like this certainly won't hurt. Even if they only increase security by a tiny amount, they're so quick and easy to implement that there's no reason not to use them.

Adding the following snippet to your functions file will remove the WordPress version number not only from your posts and pages, but from your feeds as well.

// Remove WordPress version number
function megademic_remove_version_info() {
    return '';
}
add_filter( 'the_generator', 'megademic_remove_version_info' );

If you have a dedicated security plugin such as Wordfence or Sucuri installed (and if not, why not?), you won't need to add any code to your functions file; the plugin will take care of it for you.

You've spent ages carefully organising your content to provide the best user experience possible. You've excluded certain post categories from showing on the homepage. You've excluded a few categories from your related posts plugin. You've even set a few categories to be "invisible". And then someone uses the search box and all hell breaks loose.

You see, the default WordPress search function obliterates all of these distinctions. The built-in search widget will pull in every post and page that matches the chosen term, breaking the segmentation of your site. It may well surface content that wouldn't fit what a casual visitor is looking for, and that's not going to help you put bread on the table.

To prevent certain categories of posts from appearing in the internal search results, simply copy and paste the following snippet into your functions.php file. Of course, you'll need to replace the category ID numbers "6, 13" with those of the categories you wish to exclude.

// Exclude categories from search
function megademic_category_search_filter( $query ) {
    if ( $query->is_search &amp;&amp; ! is_admin() ) {
        $query->set( 'cat', '6, 13' ); 
    }
    return $query;
}
add_filter( 'pre_get_posts', 'megademic_category_search_filter' );

If there's a distinct separation between your blog posts and your regular business pages, it doesn't make sense to have the latter appear in search results. To exclude your pages from appearing in the search results, add the code below to your functions file.

// Exclude pages from search
function megademic_exclude_pages_from_search( $query ) {
    if ( $query->is_search ) {
        $query->set( 'post_type', 'post' );
    }
    return $query;
}
add_filter( 'pre_get_posts', 'megademic_exclude_pages_from_search' );

Disable image scaling

With the release of WordPress 5.3 came a new feature that forces large images to scale down in size to make them "web-ready". Basically, if you upload an image larger than the default threshold (2560px), WordPress will automatically scale it down.

This kind of hand-holding is becoming commonplace with WordPress, and it's really starting to grate. If I want to upload large images for design purposes (such as landing page backgrounds) I'll jolly well upload them, whether WordPress likes it or not.

So how do you prevent WordPress from taking your big, beautiful images and hacking them about to make them fit their notion of what a big image looks like? Simple. Just add the snippet below to your functions file.

// Disable image scaling
add_filter( 'big_image_size_threshold', '__return_false' );

Including images in your RSS feed will help to improve content syndication and is also helpful for email marketing platforms like Mailchimp, which uses RSS (Really Simple Syndication) to create automated RSS email campaigns.

Unfortunately there's no magic button in WordPress to show featured images in your RSS feeds, but it's easy enough to achieve by using a plugin like Featured Images in RSS for Mailchimp, or by adding the following code snippet to your functions file.

// Add featured images to RSS feeds
function megademic_rss_featured_image( $content ) {
    global $post;
    if( is_feed() ) {
        if ( has_post_thumbnail( $post->ID ) ) {
            $prepend = '<div>' . get_the_post_thumbnail( $post->ID, 'medium', array( 'style' => 'margin-bottom: 10px;' ) ) . '</div>';
            $content = $prepend . $content;
        }
    }
    return $content;
}
add_filter( 'the_content', 'megademic_rss_featured_image' );

Delay posts appearing in feeds

Thank goodness for Gmail's email undo button. No more accidentally sending offensive jokes to your boss instead of your mates. The flirty email you sent to a work colleague after a boozy night out can be unsent at the click of a button. And your neighbour doesn't really need to know it was you who reversed into their car, do they? Thank goodness for the Gmail undo button.

If only there was something like that for blog post RSS feeds. Actually, there is, sort of. It's the posts_where filter, and it's pretty powerful.

If you copy and paste the following snippet into your functions file, your posts won't show up in your RSS feeds until one hour after they've been published. This will give you plenty of time to correct any mistakes you've made.

If you want to increase the delay, simply change the "1" to a "2" or "3", or whatever you like.

// Delay posts appearing in RSS feeds
function megademic_delay_rss( $where ) {
    global $wpdb;
    if ( is_feed() ) {
        $where .= " AND TIMESTAMPDIFF( 'HOUR', $wpdb->posts.post_date_gmt, '" . gmdate( 'Y-m-d H:i:s' ) . "' ) > 1 ";
    }
    return $where;
}
add_filter( 'posts_where', 'megademic_delay_rss' );

Change the length of your post excerpts

Depending on your theme, it's likely that your blog archives display brief excerpts of your posts to give readers a better idea of what the content is about.

Excerpts are restricted to 55 words by default. While this is usually enough for most sites, there may be times when you want to extend this – particularly if your content is more technical in nature.

The following snippet will extend the excerpt limit to 80 words. If you want to increase/decrease the limit, just change the number to your desired value.

// Change the length of your post excerpts
function megademic_excerpt_length( $length ) {
    return 80;
}
add_filter( 'excerpt_length', 'megademic_excerpt_length' );

Upload SVG images

By default, WordPress enables you to upload a very limited range of file types, such as .jpg, .png, .gif, .pdf, .mp3 and .mp4.

So what do you do if you want to use .svg images? SVGs offer infinite resolution, are smaller in size (which means they load faster) and allow for animation and styling. They're perfect for logos, icons and other simple graphics. And more and more websites are embracing them.

Which brings me back to how to add them to your site. You have a couple of options: You can either use a plugin such as the very popular SVG Support…or, you guessed it, you can add the simple snippet below to your functions file.

// Upload SVG images
function megademic_mime_types( $mime_types ) {
    $mime_types[ 'svg' ] = 'image/svg+xml';
    return $mime_types;
}
add_filter( 'upload_mimes', 'megademic_mime_types', 1, 1 );

Enable shortcodes in widgets

By default, shortcodes can't be run inside of text widgets, but adding the following snippet to your functions file will right that particular wrong. You could also install the Shortcodes Anywhere plugin if you want to use shortcodes, well, anywhere.

// Enable shortcodes in widgets
define( 'widget_text', 'do_shortcode' );

Disable curly quotes

If you've ever copied and pasted content into your WordPress editor, you've probably noticed that it automatically converts "straight" quotation marks into "curly" ones. Usually that won't do any harm, but if you copy and paste some kind of code snippet it could break that snippet.

To prevent WordPress from changing straight quotes to curly quotes, add the small snippet below to your functions file.

Only a small change, but a very useful one.

// Disable curly quotes
remove_filter( 'the_content', 'wptexturize' );

Change the width of the Gutenberg editor

If you find yourself needing to organise your content into multiple columns, you may encounter a rather annoying problem: the width of the Gutenberg editor is far too narrow.

In fact, the default width of the Gutenberg editor is just 610px – a strange design choice, given that the WordPress team clearly want Gutenberg to compete with dedicated pagebuilders like Elementor, Brizy, Oxygen and Divi.

To compound the issue, there's no obvious way to increase the width of the editor; there's no option in the WordPress dashboard, and the documentation for customising Gutenberg is buried in the Block Editor Handbook. Thankfully, customising the width of the editor to suit your needs is relatively easy when you know how.

The first thing you'll need to do is create a CSS file called style-editor.css and add the following code to it, changing the widths to suit your needs.

/* Main column width */
.wp-block { max-width: 100%; }
 
/* Width of "wide" blocks */
.wp-block[data-align="wide"] { max-width: 100%; }
 
/* Width of "full-width" blocks */
.wp-block[data-align="full"] { max-width: none; }

Once you've done that, include style-editor.css in your WordPress theme by adding the following code snippet to your functions.php file.

// Load Gutenberg editor styles
function megademic_gutenberg_editor_styles() {
    wp_enqueue_style(
        'admin-styles',
        get_stylesheet_directory_uri().'/style-editor.css'
    );
}
add_action( 'admin_enqueue_scripts', 'megademic_gutenberg_editor_styles' );

The next time you edit a page or post, you'll notice that the Gutenberg editor spans the full width of the screen, making it much easier to visualise your content – especially when creating complex, multi-column layouts.

Update to the latest version of jQuery

For a company that's always telling its users to keep WordPress up-to-date, it seems more than a touch hypocritical that Automattic (the authors of WordPress) have shipped the platform with an out-dated version of jQuery for years.

The current version of jQuery that's bundled with WordPress – and has been since 2016 – is 1.12.4, which has known security issues and also supports Internet Explorer 6, 7 and 8. Not ideal.

If you want to upgrade to the latest version of jQuery (3.5.1 at the time of writing) and benefit from performance improvements, security fixes and various other goodies, simply pop the following code into your functions file.

Just make sure your themes and plugins are compatible with it before you do.

// Update jQuery to version 3.5.1
if ( !is_admin() ) {
    wp_deregister_script( 'jquery' );
    wp_register_script( 'jquery', ("https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"), false );
    wp_enqueue_script( 'jquery' );
}

Defer passing of JavaScript

What do Google and Keanu Reeves have in common? They both feel the need, the need for speed!

In case you've been living on Mars for a while, Google now values website speed as much as users do, so it pays to go the extra mile and make your web pages load as quickly as possible. And one of the most effective ways to reduce the time it takes for your visitors to see your design and content is to defer your JavaScript files.

So what do I mean by defer? Well, there are three ways to load JavaScript files: block (the default method), defer and async.

If you include your JavaScript using just the <script> tag, the HTML on your page will be parsed (rendered) until the JavaScript file it hit, at which point the parsing will stop and a request will be made to fetch the file (if it's external). The JavaScript will then be executed before parsing is resumed.

If you include your JavaScript using <script async>, the file will be downloaded at the same time as the HTML is parsed, saving precious milliseconds. The HTML will then pause while the JavaScript is executed and resumes once it has finished.

Loading a JavaScript file asynchronously is generally preferable to the blocking method as it allows parsing of HTML while the script is downloaded, but it can easily break your website. This is because there's no guarantee that scripts will finish executing in the order that they appear in the document. So if a JavaScript library (like jQuery) loads after the files that depend on it, you've got problems.

Finally there's the "defer" method. If you include your JavaScript using <script defer>, the script is downloaded as the HTML is parsed but, unlike with the "async" method, the script will only be executed once the HTML has been parsed.

Using the "defer" method can help pages render quicker, increasing the perception of speed for the visitor. Scripts that are loaded using <script defer> are also guaranteed to execute in the order that they appear in the document, which helps to reduce the risk of your page breaking.

So how do you defer JavaScript files in WordPress? That's the easy bit: all you have to do is paste the code snippet below into your functions file.

// Defer all JavaScript except jQuery
function megademic_defer_parsing_of_js( $url ) {
    if ( is_user_logged_in() ) return $url; //don't break WP Admin
    if ( FALSE === strpos( $url, '.js' ) ) return $url;
    if ( strpos( $url, 'jquery.js' ) ) return $url;
    return str_replace( ' src', ' defer src', $url );
}
add_filter( 'script_loader_tag', 'megademic_defer_parsing_of_js', 10 );

This snippet will use <script defer> to load all of your JavaScript files except jQuery. Loading the jQuery library using anything other than the default blocking method can very easily break themes and plugins, so I've excluded that file in the code above.

This is a quick and easy way to defer the loading of your JavaScript files, but it doesn't offer the same kind of control as a conditional loading plugin like Asset CleanUp Pro (the gold standard for WordPress asset management).

Have we missed a trick?

There are tons of things you can do with the functions.php file and there's a good chance we've left out a code snippet that shouldn't be left out.

If you know a useful code snippet for the WordPress functions file that we haven't included in this post, please let us know in the comments below and we'll add it to the post as soon as we can.

Rob Carter
Rob Carter

Rob Carter is a digital marketing expert with a genuine passion for helping businesses thrive online. Rob has been building websites and crafting marketing campaigns for over 20 years, and his creativity and analytical ability are highly sought after by businesses and non-profits around the world.

Articles: 67

3 Comments

  1. Howdy Rob.

    I know that you are a fan of the WP CodeBox plugin.

    I haven’t quite figured out when, where, and how that plugin serves up it’s snippets (I am not really a developer, just a long term wordpress user who often hacks things himself).

    In general, can these kinds of snippets be added there in that plugin instead of in the functions.php file?

    • Hi Jon,

      You’re right: I love WPCodeBox. It’s an amazing plugin and goes on every site I build.

      All of the snippets on this page can be used with WPCodeBox. It’s basically a graphical interface for the WordPress functions file. Of course, it also has numerous additional features such as cloud storage, drag-and-drop folders, a ready-made snippets repository, powerful conditional loading and live CSS changes.

      It’s a fantastic plugin, and one that I highly recommend.

      • Thanks for replying. 🙂

        Nice.

        I had thought WP Codebox worked like that.

        I’ve only done a little bit with it, but I like it so far.

Leave a Reply to Rob CarterCancel Reply

Your email address will not be published. Required fields are marked *