WordPress functions.php File The Ultimate Guide + Helpful Code Snippets (r) (r)

Mar 29, 2023
All about the wordpress functions.php file

I'm not sure of the WordPress functions.php file does or what it can use it for?

In a nutshell, in a nutshell, the WordPress functions.php file provides you with the ability to insert code snippets of code to your site. You can use these snippets in all kinds of helpful methods, and understanding how the functions.php function can assist in building a stronger WordPress website.

The ultimate guide for functions.php in the WordPress functions.php file we'll teach you everything you should know about this file.

Once you know all about what's in the functions.php file, we'll provide 17 useful functions.php code fragments that will aid you in creating a custom website.

What Does the WordPress functions.php File Actually Do?

It is the WordPress functions.php document is a theme file that is used to insert specific code fragments on your website. These code snippets to change the way the various sections of your website work or to add new code/content to your website.

Although it is part of your theme however, even though it is part of your theme, WordPress functions.php file isn't strictly limited to making changes to your theme.

You can make adjustments to every aspect of your website like how plugins function.

These are the most common kinds of adjustments that you can do using the WordPress functions.php file:

  • Change core WordPress behavior, for example how many pages to display on the search results page or what information to put on your website's RSS feed.
  • Design your own customized shortcodes.

This is just scratching the layer...

Where Is the WordPress functions.php File Located?

What is the best way to work safely with the functions.php File

Since using functions.php in the WordPress functions.php file involves adding code to your website you must follow certain best practices prior to you begin making changes to your website.

But still - to avoid problems from occurring, we always recommend following these guidelines...

Try Your functions.php The code is displayed on a staging Website

Before adding any functions.php code snippets to your live WordPress site, we always advise testing them using the staging version of your website first. It allows you to check for any potential errors and verify the code snippet you've added is working as intended.

Make sure to backup your site prior to Making changes to functions.php

In addition to testing using a staging website It is also recommended to back up your live website before adding the code snippet to your live site's functions.php file.

If anything goes wrong in the code, you can restore to this backup point and instantly have the site back to normal.

Always Use a Child Theme If You're Editing the functions.php File

To ensure that the modifications that you have made to the theme's functions.php file become obsolete, you should always choose the functions.php file in a WordPress child theme. Then, you can add your code snippets to within the functions.php file in the theme's child.

If you use an additional theme as a child, you're still able to modify the parent theme as needed, but the entirety of your functions.php adjustments will never be duplicated.

2 functions.php File Alternatives that Could Work Better

Although the WordPress functions.php file is an easy way to add code fragments on your website however, there are other functions.php alternatives that can provide a better solution in most circumstances:

  1. Using a code manager plugin
  2. The code snippets are stored inside a plugin that is custom

These alternatives can have a number of benefits over the functions.php file:

  • Does not depend on the theme you are using It means if you ever change themes, your functions.php modifications will remain present.
  • Improved organization- these alternatives make it simpler to arrange your code snippets. This is beneficial when you intend to incorporate many code snippets to your site.
  • Greater controlWhen you make use of a plugin for code management, you get helpful options for enabling and disabling snippets using a toggle button, only running snippets on the frontend or backend, and many more.

Make use of a Code Manager plugin

A code manager plugin is a plugin that gives you the user-friendly way to insert and edit code snippets that would otherwise go into your functions.php file.

One of the most well-known alternatives is the free Code Snippets plug-in However, you may find other plugins that offer similar functionality.

With Code Snippets You can include to your functions.php code snippets directly from the WordPress dashboard, complete with options to...

  • Add a title and description.
  • Sort your notes using tags.
  • You should only use the snippet for only a specific part of your website.
Adding a code snippet in the Code Snippets plugin.
Adding a code snippet in Code Snippets plugin. Code Snippets plugin.

Then, you can view all of your snippets in a list and easily disable or enable them as you need to.

How to manage snippets in Code Snippets.
How to manage snippets in Code Snippets.

Create a custom feature plugin

An alternative to the WordPress functions.php file is to just create your own custom plugin for storing the code snippets.

While this might sound complicated but it's actually much less complicated than you think.

Here's how it works:

  1. Create a folder on the local computer for your plugin.
  2. Create a single .php file within the folder, and then edit it using your preferred editor for text.
  3. Incorporate the code template provided below into the file.
  4. Add your functions.php code to the file

After that, all you have to do is to install and then activate the plugin in WordPress. There are two ways to do that:

  1. Use your computer to create an .zip file from the directory. Then, go to the Plugins tab > Create New and upload the .zip file. You can then install it exactly like other plugins.

How To Access the WordPress functions.php File There are two options

There are a variety of ways users can edit and access this WordPress functions.php files. These are the two most versatile methods that will be compatible with any hosting platform:

  1. WordPress in-dashboard theme code editor.
  2. SFTP and your own code editor.

1. Use the WordPress In-Dashboard Theme Code Editor

As a by default WordPress permits you to modify every single line of code in your theme through your WordPress dashboard. This includes the functions.php file:

  1. Open your WordPress dashboard.
  2. Go to the Appearance tab and then to the Theme Editor.
  3. Click on your theme functions (functions.php) file in the Theme Files list on the right-hand side.
  4. Edit your code into the code editor.
  5. Click on the update file button to save your changes.
How to edit the functions.php file from your WordPress dashboard.
How to edit the functions.php file on your WordPress dashboard.

2. Utilize SFTP and Your own Code Editor

Here's how:

  1. Use the folder structure to navigate to .../wp-content/themes/[your-active-child-theme]
  2. Right-click the functions.php file and choose edit.
How to edit the functions.php file with FileZilla.
How do I edit the functions.php file with FileZilla.

This should download the file to your local computer and immediately open it with an editor for text. It is now possible to add code snippets to the file.

FileZilla will open the file in a local text editor -- e.g. Sublime Text.
FileZilla can open the file in an editor for local use- e.g. Sublime Text.

After you're finished you can save the changes and close the file.

FileZilla will then display an option to upload the modified version of your server.

Make sure to reupload the functions.php file once you've made your changes.
It is important to download the functions.php file following modifications.

Top Useful Functions to Add to your WordPress functions.php File

Once you've learned how to modify your WordPress functions.php file, let's go over some of the most useful functions.php code fragments you can incorporate into your blog.

Update Dates on Blog Posts

By default, most themes show the date that you published a blog post. If you're constantly revising and updating old posts You may want to display the latest updated date (or substitute the date of publication with the last modified date).

This not only lets the people who visit your site know you're constantly updating your information, but is also a signal to Google that the content you've posted is current.

function show_last_updated( $content ) 
 $u_time = get_the_time('U');
 $u_modified_time = get_the_modified_time('U');
 if ($u_modified_time >= $u_time + 86400) 
 $updated_date = get_the_modified_time('F jS, Y');
 $updated_time = get_the_modified_time('h:i a');
 $custom_content .= 'Recently updated on '. $updated_date . ' at '. $updated_time . "/p>";$custom_content .= $contentreturn $custom_content;
 
add_filter(  the_content', show_last_updated' );

Deleting the WordPress Toolbar on Certain Users

If you'd like to alter thisfeature, you could apply the functions.php code fragment to block the WordPress toolbar on certain users roles.

In this example, you would use administrators to use the admin toolbar on behalf of those with the author job.

add_filter( 'show_admin_bar', function( $show ) show $show return; );

Delay Posts from Appearing In RSS Feed

To avoid having someone else be credited for your post You can block content from being included on Your RSS feed.

Though this will not stop scrapers of content, it can suggest that you should allow Google time to crawl your site's content before they index it.

This is the code snippet that you can use - You can alter the number - "30" as in the instance and change it to the length of time you'd like the delay to be:

function _delay_feed_content($where) 
 
 global $wpdb;
 
 if ( is_feed() ) 
 // timestamp in WP-format
 $now = gmdate('Y-m-d H:i:s');
 
 // value for wait; + device
 $wait = '30'; // integer
 
 // http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_timestampdiff
 $device = 'MINUTE'; //MINUTE, HOUR, DAY, WEEK, MONTH, YEAR
 
 // add SQL-sytax to default $where
 $where .= " AND TIMESTAMPDIFF($device, $wpdb->posts.post_date_gmt, '$now') > $wait ";
 
 return $where;
 
 
 add_filter('posts_where', '_delay_feed_content');

Exclude Certain Categories From RSS Feed

As well as preventing material from appearing in your RSS feed, it is could have instances where you want to exclude whole categories of blog content from showing up in your site's RSS feed.

For this purpose, you can use these functions.php Code snippets:

function _exclude_category_rss($query) 
 if ($query->is_feed) 
 $query->set('cat','-38');
 
 return $query;
 
 add_filter('pre_get_posts','_exclude_category_rss');

Be sure that you substitute the sample ID for the category"38 "38" - with the actual category IDs that you wish to eliminate (and do not take out the minus)

This is how you can find the ID number:

  1. Visit Categories of Posts for a listing of all the categories you have on your website.
  2. Make sure to click Edit in the category you wish to remove.
  3. Look at your edit page within your browser's address bar. The category ID is the number that comes after ?taxonomy=category&tag_ID=X.

For example, if the URL is https://yoursite.com/wp-admin/term.php?taxonomy=category&tag_ID=38&post_type=post, then the category ID is 38.

Limit WordPress revisions per Post Type

In order to avoid overflowing your website's database, it might be beneficial to limit the number of revisions are saved.

This functions.php code block can be used to accomplish exactly what you want to do. To customize it to your needs alter the post type - "post" in this example for the exact type of post you wish to regulate and set the number - "5" within this case is the number of revisions that you want to store.

function _post_revisions_by_type( $revisions, $post ) 
 
 if( 'post' == $post->post_type ) 
 $revisions = 5;
 
 
 return $revisions;
 
 
 
 add_filter( 'wp_revisions_to_keep', '_post_revisions_by_type', 10, 2 );

It is important to note that you are editing the "post" that comes right after the "if" sentence. For example, to target products, that line would be like this:

if( 'product' == $post->post_type ) {

Disable the WordPress Search Function

As an example, even though there isn't a search box on your website, bots can still use the search feature by adding ?s=[search-term] to your URL.

For this, you can include the code in this snippet:

function _disable_wp_search( $query, $error = true ) 
 
 if ( is_search() ) 
 $query->is_search = false;
 $query->query_vars[s] = false;
 $query->query[s] = false;
 
 // to error
 if ( $error == true )
 $query->is_404 = true;
 
 
 
 add_action( 'parse_query', '_disable_wp_search' );
 add_filter( 'get_search_form', create_function( '$a', "return null;" ) );

If someone tries to search on your website, it will return a 404 page instead.

Create Your own customized shortcodes (E.g. the current year)

Although many WordPress plugins rely on shortcodes for their functionality, you can make your own customized shortcodes by using your WordPress functions.php file, and the create_shortcode() function.

For example, one common use case is to create shortcodes that display the year currently in use. It allows you to automatically display the current year across the content you publish without having to update your content manually on January 1st every year.

To create such shortcodes, use this code:

function year_shortcode() 
 $year = date('Y');
 return $year;
 
 add_shortcode('currentyear', 'year_shortcode');

If you later insert the shortcode [currentyear] in your post the shortcode will be automatically substituted with the year of the present - e.g. 2023.

Allow Shortcodes in Post Titles

As a by default WordPress won't execute any shortcodes you put in the title of your post. If you'd like to include shortcodes in WordPress post titles, you can enable this functionality by adding a simple code snippet in within the WordPress functions.php files.

For example, when combined with the code you used previously it will allow you to instantly include the year in question in the post's title with the addition of the shortcode [currentyear].

add_filter( 'the_title', 'do_shortcode' );

Remove Login Errors and Improve Security

As a default, WordPress shows an explaining message after failed login attempts. This message can give away certain information, for example the likelihood that a particular email address has been registered on your site (even if the password is incorrect).

To ensure that you do not leak any sensitive information, hide these login errors with the help of this fragment to the functions.php file.

function _hide_login_errors()
 return 'These are not valid credentials';
 
 add_filter( 'login_errors', '_hide_login_errors' );

This snippet replaces the login error message default with the following message - These are not valid login credentials.

The text can be customized according to your preferences - However, try not to use dashes, slashes or other characters , as they may cause errors (unless it is possible to "escape" those characters),

Alter the Excerpt Length

The default WordPress excerpt displays the first 55 lines of the post.

If you'd like to modify this, insert the following code fragment in this functions.php file.

function _change_excerpt_length($length) 
 return 90;
 
 add_filter('excerpt_length', '_change_excerpt_length');

The code snippet above will change the excerpt length by 90 words. If you'd like a different number, you can change "90" to the exact number of words that you'd like to utilize.

Take out the WordPress Version Number

To make it harder for malicious actors to detect which version of WordPress that you're running, some users would prefer to remove this WordPress Version number being displayed on any page's frontend software.

In order to do this, you can incorporate the code below in within your functions.php file.

function _hide_version() 
 return '';
 
 add_filter('the_generator', '_hide_version');

Install WordPress WordPress Pagination

If you're not happy by the way pagination functions in your theme, make use of a functions.php code snippet that allows you to alter the how pagination behaves or create your own pagination system.

Variate the number of results to include on the Search Listing Page

WordPress gives you an in-dashboard option to control how many posts to list on pages with archive content ( Settings - Reading).

This will change the number used that is used for the entire archives pages. What if you just want to use a different number for the search results page?

For that, you can incorporate this code into your functions.php file. Be sure you change the value ("12" for this case) to the actual number of results you would like to display prior to paginating additional results.

function _search_results_list() 
 if ( is_search() )
 set_query_var('posts_per_archive_page', 12);
 
 
 add_filter('pre_get_posts', '_search_results_list');
function _featured_image_rss($content) 
 global $post;
 if ( has_post_thumbnail( $post->ID ) )
 $content = '' . get_the_post_thumbnail( $post->ID, 'full', array( 'style' => 'margin-bottom: 15px;' ) ) . '' . $content;
 
 return $content;
 
 
 add_filter('the_excerpt_rss', '_featured_image_rss');
 add_filter('the_content_feed', '_featured_image_rss');

The above code will display the image with the full size. If you want to use a different thumbnail size, change "full" to another size thumbnail - e.g. "large" as well as "medium".

Update Upload Support to file types (E.g. SVG)

To enable support for these blocked file types, you can add the following code fragment in within the WordPress functions.php file:

function _myme_types($mime_types)
 $mime_types['svg'] = 'image/svg+xml';
 return $mime_types;
 
 add_filter('upload_mimes', '_myme_types', 1, 1);

This code snippet is only capable of SVG uploads. You may modify it to provide support for different file types when needed.

Remove WordPress Update Nags for Users Other than Administrators

However, if the user's position doesn't allow them to apply the update The dashboard will instruct the user to reach out to the administrator.

If you want to alter this setting, apply this code snippet in order to disable update notifications to any non-Administrator user:  function _hide_update_nag()  if ( ! current_user_can( 'update_core' ) )  remove_action( 'admin_notices', 'update_nag', 3 );   add_action('admin_menu','_hide_update_nag');

Automatically Change JPEG Quality Optimization

In WordPress 4.5, WordPress has changed the default quality setting to 82 (with 100 representing zero compression).

If you wish to set this quality level more or lower, incorporate the following code snippet into your functions.php file - make sure to change the number ("90" for this case) to reflect the quality level you wish to utilize:

add_filter( 'jpeg_quality', create_function( '', 'return 90;' ) );

Tips for organizing Your WordPress functions.php File

If you're using only the WordPress functions.php document to include some code snippets, you probably don't need to worry about organization.

However, if you're adding large number of code-related snippets onto your website, it could quickly get unwieldy and complex when you're not adhering to certain functions.php guidelines for organizing files.

Here are a few best practices to keep your code snippets in order...

Comment Codes to Define Everything

When you first add a code snippet to the functions.php file, you will know exactly what it is and the reason you put it there. However, if you go back at the functions.php file after a year it may not be as clear.

To avoid this You should make code-related comments on each fragment that describe what the snippet does and why you've added it.

  Comments on code are the text that isn't executed by WordPress however, humans can read in order to know what the code is doing.  

If you want to add a single line code-related comment, use this format:

/The code is one-line code-related comment

If you want to add a multi-line code comment, you may make use of this form:

 ** This is a code-related comment that extends across multiple linesThis is within the same code comment*This is the final line in the code comment
 *

Here's an example of how you might utilize code comments. You will notice that the note at the beginning of each code snippet describes what the snippet does.

An example of using code comments to document snippets in the functions.php file.
A case study of how to use code comments to document snippets in the functions.php file.

Make use of Include Files to divide Snippets Into Different Files

If you're really stuffed with lots of code snippets, you can store them in separate files instead of using just the functions.php file.

Then, you can include those code snippets in the functions.php file using including or requiring. Mike Schinkel has a excellent instance of how to do this on StackExchange.

Consider One of the functions.php Alternate Options from the Above

If you find your functions.php file becoming a little messy, then you may want to consider some of the functions.php alternatives we discussed earlier.

In this case, the free Code Snippets plugin makes it very easy to manage everything since you can add each code snippet individually, with its own description and title. description. Tags can be used to categorize your snippets.

Summary

This WordPress functions.php files is one of the theme-specific script that allows you to include PHP codes to your website.

If you want to add code snippets to your functions.php file, you should always use the child theme in order to ensure the changes you make don't become obsolete when you update your theme. It is also recommended to backup your website before adding any snippets and trying them out on a test site whenever possible.

As an alternative to making use of functions.php as a substitute for the functions.php document, you could think about a code management plugin, or even creating your own customized plugin that will house the code snippets you have created.

Once you understand how the WordPress functions.php file works and how it works, you are able to begin customizing your website in a variety of helpful ways.

The sample functions.php excerpts below will give you some good places to begin, but there's no limit in terms of what you're able accomplish.

  • It is easy to set up and manage My dashboard. My dashboard
  • Support is available 24/7.
  • The best Google Cloud Platform hardware and network powered by Kubernetes to ensure maximum capacity
  • A high-end Cloudflare integration to speed up as well as security
  • Global audience reach with up to 35 data centers as well as 275 PoPs worldwide