Tel: +44 1737 516331

Useful Tricks for Your WordPress Functions File

Last updated on by

Disclaimer: This post may contain affiliate links. If you purchase something through one of those links you won’t pay a penny more, but we’ll get a small commission.

Change how WordPress works

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 the expertise of a web designer or developer, 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. Also, be sure to check out our guide to the WordPress functions.php file, where you’ll find lots more helpful information.

Stop!

Before proceeding any further, do yourself a favour and make a backup of your site. It’s much better to have a default WordPress website than a broken WordPress website.

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.

Edit the functions file using FTP - step 1
FileZilla login form

2. After you’ve entered your details, click the “Quick connect” button.

Edit the functions file using FTP - step 2
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]/”.

Edit the functions file using FTP - step 3
WordPress theme folder

4. Next, right-click your theme’s functions.php file and click “Download” to download it to your local machine.

Edit the functions file using FTP - step 4
Download the functions file

5. Then open the file in your favourite code editor (I use Sublime, 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.

Edit the functions file using FTP - step 6
Upload the functions file

Now you know how to edit the functions file, let’s get pimping your WordPress website!

Functions file code snippets

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, bringing more 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 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( 'jpeg_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 remove_version_info() {
    return '';
}
add_filter( 'the_generator', '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.

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.

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 RSS 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 have 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 past 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.

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.

function megademic_excerpt_length( $length ) {
    return 80;
}
add_filter( 'excerpt_length', 'megademic_excerpt_length' );

Upload any file type

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.

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.

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.

remove_filter( 'the_content', 'wptexturize' );

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 know about a useful trick for the WordPress functions file that we haven’t covered in the post, please let us know in the comments below and we’ll add it to the post as soon as we can.

Take the next step

Subscribe to our newsletter, where we share actionable advice and useful tips for building your brand and growing your online business.

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on reddit
Reddit

You may also like:

Leave a Reply

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