WordPress functions.php File: The Ultimate Guide + Helpful Code Snippets
Not sure what the WordPress functions.php file is or what you can do with it?
In a nutshell, the WordPress functions.php file gives you a way to add code snippets to your site. You can use these snippets in all kinds of helpful ways, so understanding how the functions.php file works can help you build a better WordPress site.
In our ultimate guide to the WordPress functions.php file, you’re going to learn everything that you need to know about this file.
Once you know all about the functions.php file, we’ll also share 17 helpful functions.php code snippets to help you start customizing your site.
What Does the WordPress functions.php File Do?
The WordPress functions.php file is a theme file that you can use to add custom code snippets to your site. You can use these code snippets to modify how different areas of your site function or add new content/code to your site.
Despite being included in your theme, the WordPress functions.php file is not limited to just making customizations to your theme.
You can make adjustments to any part of your site, similar to how plugins work.
Here are some common types of adjustments that you can make using the WordPress functions.php file:
- Change core WordPress behavior, such as how many posts to show on the search results page or what content to include in your site’s RSS feed.
- Create your own custom shortcodes.
- Add new content or scripts to your site, such as injecting a script from your live chat service on certain pages or editing your site’s footer.
This is just scratching the surface…
Because the functions.php file lets you add custom PHP code snippets to your site rather than static HTML, the sky’s the limit when it comes to the types of modifications that you can make.
Where Is the WordPress functions.php File Located?
The WordPress functions.php file is located in your active theme’s folder, along with other theme files. To find the file, you can connect to your server using FTP or a file manager tool and browse to …/wp-content/themes/[active-theme-name]/functions.php
For example, if you’re using the popular OceanWP theme, the functions.php file would be located at …/wp-content/themes/oceanwp/functions.php
How To Safely Work With the functions.php File
Because working with the WordPress functions.php file involves adding code to your website, it’s important to follow some best practices before you start making any edits.
Even something as simple as a missing comma or apostrophe can trigger errors on your site, such as the WordPress White Screen of Death.
In recent versions of WordPress, WordPress has gotten better at handling these errors in a more graceful way, such as showing the “There has been a critical error on your website” message or checking for PHP errors before saving your changes.
But still – to avoid any issues from happening, we always recommend following these best practices…
Test Your functions.php Code on a Staging Site
Before adding any functions.php code snippets to your live WordPress site, we always recommend testing them on a staging version of your site first. This lets you check for any potential errors and verify that the code snippet is working as intended.
If you host with Kinsta, Kinsta offers an easy 1-click staging tool on all plans, which is one of the benefits of using managed WordPress hosting.
If you’re hosting elsewhere, you can check out our guide on setting up a WordPress staging site.
Back Up Your Site Before Making Changes to functions.php
In addition to testing on a staging site, you’ll also want to back up your live website before adding the code snippet to your live site’s functions.php file.
This is a good best practice to follow when editing any WordPress files.
If anything goes wrong with the code snippet, you can restore to this backup point to instantly get your site working again.
If you host with Kinsta, Kinsta automatically backs up your site every day and you can also manually create a backup at any time. If you host elsewhere, you can read our guide on how to back up a WordPress site.
Always Use a Child Theme If You’re Editing the functions.php File
Because the WordPress functions.php file is located in your WordPress theme’s code, your theme will overwrite the functions.php file when you update your theme.
To avoid having the changes that you made to your theme’s functions.php file overwritten, you should always use a WordPress child theme and add your code snippets to the functions.php file in the child theme.
By using a child theme, you’re still able to update the parent theme when needed, but all of your functions.php customizations will never be overwritten.
To learn more, check out our full guide on how to create a WordPress child theme.
2 functions.php File Alternatives That Might Be Better
While the WordPress functions.php file offers an easy way to add code snippets to your site, there are some functions.php alternatives that offer a better solution in most situations:
- Using a code manager plugin
- Storing code snippets in a custom plugin
These alternatives can have a few advantages over using the functions.php file:
- Not tied to your theme – this means that if you ever change themes, your functions.php customizations will still be there.
- Better organization – these alternatives make it easier to organize your code snippets, which can be helpful if you plan to add a lot of code snippets to your site.
- More control – in the case of a code manager plugin, you get helpful options such as enabling/disabling a snippet using a toggle button, only running snippets on the frontend or backend, and more.
Use a Code Manager Plugin
A code manager plugin is a plugin that gives you a user-friendly interface to add and edit code snippets that would otherwise go in the functions.php file.
One of the most popular options is the free Code Snippets plugin, but you can find other plugins that offer similar functionality.
With Code Snippets, you can add your functions.php code snippets from the WordPress dashboard, complete with options to…
- Add a title and description.
- Organize your snippets using tags.
- Only run the snippet on a certain part of your site.
You can then see all of your snippets in a list and easily enable/disable them as needed.
Because Code Snippets is a plugin, all of your code snippets will still be there even if you change WordPress themes.
Create a Custom Feature Plugin
Another alternative to the WordPress functions.php file is to just create your own custom plugin to house the code snippets.
While this might sound complicated, it’s actually a lot simpler than it might seem.
Here’s how it works:
- Create a folder on your local computer for your plugin.
- Create a single .php file inside that folder and edit it with your favorite text editor.
- Add the code template below to the file.
- Add your functions.php code snippets to the file
<?php
/**
* Plugin Name: My Custom Code Snippets
* Description: This is a custom plugin to house code snippets.
* Author: Kinsta
* Version: 1.0
*/
/* Add the first code snippet below this comment - use the comment to explain what it does. */
[CODE]
/* Add the second code snippet below this comment. */'
[CODE]
/* Continue as needed. */
[CODE]
?>
Then, you just need to install and activate the plugin on WordPress. Here are 2 ways to do that:
- Connect to your server via FTP/SFTP and upload the custom plugin folder to the wp-content/plugins folder. Then, go to the Plugins list and activate the plugin.
- Use your computer to create a .zip file of the folder. Then, go to Plugins → Add New and upload the .zip file to install it just like any other plugin.
How To Access the WordPress functions.php File: 2 Options
There are different ways that you can access and edit the WordPress functions.php file. Here are 2 of the most versatile methods that will work at any host:
- WordPress in-dashboard theme code editor.
- SFTP and your own code editor.
1. Use the WordPress In-Dashboard Theme Code Editor
By default, WordPress lets you edit all of your theme’s code from your WordPress dashboard, including the functions.php file:
- Open your WordPress dashboard.
- Go to Appearance → Theme File Editor.
- Select the Theme Functions (functions.php) file in the Theme Files list on the right-hand side.
- Add your edits in the code editor.
- Click the Update File button to save your changes.
With that being said, many people like to disable WordPress in-dashboard file editing to improve security. In that case, you can use the next method.
2. Use SFTP + Your Own Code Editor
For another way to edit the WordPress functions.php file, you can connect to your server via FTP/SFTP and edit the file that way.
Here’s how:
- Download an FTP client if you haven’t done so already – we’ll use the free FileZilla client for the screenshots.
- Connect to your server using your FTP credentials – here’s how to use SFTP to connect.
- Use the folder structure to navigate to …/wp-content/themes/[your-active-child-theme]
- Right-click on the functions.php file and select Edit.
This should download the file to your local computer and automatically open it in a text editor. You can now add your code snippets to the file.
When you’re finished, save your changes and close the file.
FileZilla should then show a prompt to re-upload the edited version to your server.
Top Useful Functions to Add to Your WordPress functions.php File
Now that you know how to edit the WordPress functions.php file, let’s go over some of the most useful functions.php code snippets that you can add to your site.
Show Last Modified Date on Blog Posts
By default, most themes show the date that you published a blog post. However, if you’re regularly updating and refreshing old content, you might want to also show the last modified date (or replace the publish date with the last modified date).
Not only does this let your human visitors know that you’re still updating the content, but it also shows Google that your content is fresh.
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 .= '<p class="last-updated-date">Recently updated on '. $updated_date . ' at '. $updated_time .'</p>';
}
$custom_content .= $content;
return $custom_content;
}
add_filter( 'the_content', 'show_last_updated' );
For more details, check out our full post showing the last modified date on WordPress.
Disable the WordPress Toolbar for Certain Users
By default, WordPress shows the WordPress toolbar for all logged-in users using the built-in WordPress user roles. This isn’t necessarily the case for custom roles, such as the Customer user role for WooCommerce stores.
If you want to change this, you can use a functions.php code snippet to hide the WordPress toolbar for certain user roles.
This example would hire the admin toolbar for users with the author user role.
add_filter( 'show_admin_bar', function( $show ) {
if ( current_user_can( 'author' ) ) {
return false;
}
return $show;
} );
Delay Posts from Appearing In RSS Feed
By default, content appears in your RSS feed as soon as you publish it. This can give content scrapers a chance to scrape your content and index it in Google before Google even indexes your original post.
To avoid having someone else get the credit for your content, you can delay posts from appearing in your RSS feed.
While this won’t completely stop content scrapers, it does mean that you can give Google time to index your content first.
Here’s the code snippet – you can change the number – “30” in this example – to the number of minutes you want the delay to be:
function kinsta_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', 'kinsta_delay_feed_content');
Exclude Certain Categories From RSS Feed
In addition to delaying content from appearing in the RSS feed, you also might have situations where you want to exclude entire categories of blog posts from appearing in your site’s RSS feed.
To achieve this, you can use the following functions.php code snippet:
function kinsta_exclude_category_rss($query) {
if ($query->is_feed) {
$query->set('cat','-38');
}
return $query;
}
add_filter('pre_get_posts','kinsta_exclude_category_rss');
Make sure to replace the example category ID – “38” – with the actual category IDs that you want to exclude (and don’t remove the minus sign)
Here’s how to find the ID number:
- Go to Posts → Categories to see a list of all the categories on your site.
- Click Edit under the category that you want to exclude.
- Look at the URL of the edit page in your browser 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 by Post Type
To avoid bloating your site’s database, you might want to limit how many post revisions to save.
While one way to limit WordPress post revisions sitewide is to edit your site’s wp-config.php file, you might want to store different numbers of revisions for different post types – e.g. blog posts versus WooCommerce products.
This functions.php code snippet lets you do just that. To make it your own, change the post type – “post” in this example – to the actual post type that you want to control and the number – “5” in this example – to the number of revisions that you want to store.
function kinsta_post_revisions_by_type( $revisions, $post ) {
if( 'post' == $post->post_type ) {
$revisions = 5;
}
return $revisions;
}
add_filter( 'wp_revisions_to_keep', 'kinsta_post_revisions_by_type', 10, 2 );
* Note – you’re editing the “post” that comes immediately after the “if” statement. For example, to target products, that line would look like this:
if( 'product' == $post->post_type ) {
Disable the WordPress Search Function
If your site doesn’t need search functionality, you might want to disable the WordPress search function to prevent potential abuse.
For example, even if you don’t show a search box on your site, bots can still use the search function by adding ?s=[search-term] to your URL.
To do this, you can add the following code snippet:
function kinsta_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', 'kinsta_disable_wp_search' );
add_filter( 'get_search_form', create_function( '$a', "return null;" ) );
If someone tries to use the search function directly, your site will return a 404 page instead.
Create Your Own Custom Shortcodes (E.g. Current Year)
WordPress shortcodes are really handy shortcuts that let you embed dynamic content in your site.
While many WordPress plugins rely on shortcodes to help power their functionality, you can also create your own custom shortcodes using the WordPress functions.php file and the add_shortcode() function.
For example, one common use case is to create a shortcode that displays the current year. This lets you automatically show the current year in all your content without needing to manually update everything every January 1st.
To create such a shortcode, you can use the following code:
function year_shortcode() {
$year = date('Y');
return $year;
}
add_shortcode('currentyear', 'year_shortcode');
Then, when you add the [currentyear] shortcode to your content, it will automatically be replaced with the actual year – e.g. 2023.
Allow Shortcodes in Post Titles
By default, WordPress won’t execute any shortcodes that you place in your post’s title field. If you want to use shortcodes in WordPress post titles, you can enable this functionality by adding a simple code snippet to the WordPress functions.php file.
For example, when combined with the previous code snippet, this would let you automatically include the current year in the post title by adding the [currentyear] shortcode.
add_filter( 'the_title', 'do_shortcode' );
Hide Login Errors to Improve Security
By default, WordPress will show an explainer message on failed login attempts. This message can give away some information, such as whether or not a certain email address is registered on your site (even if the password is incorrect).
To avoid leaking any potentially sensitive information, you can hide these login errors by adding the following code snippet to your functions.php file.
function kinsta_hide_login_errors(){
return 'These are not valid credentials';
}
add_filter( 'login_errors', 'kinsta_hide_login_errors' );
This snippet replaces the default login error text with the following message – These are not valid credentials.
You can customize the text according to your preferences – but try to avoid using dashes, slashes, or other characters as it can cause an error (unless you “escape” these characters),
Change the Excerpt Length
By default, the WordPress excerpt shows the first 55 words of a post.
If you want to adjust this, you can add the following code snippet to the functions.php file.
function kinsta_change_excerpt_length($length) {
return 90;
}
add_filter('excerpt_length', 'kinsta_change_excerpt_length');
The code snippet above will change the excerpt length to 90 words. If you’d prefer a different number, you can change “90” to the exact number of words that you want to use.
Remove the WordPress Version Number
To make it harder for malicious actors to detect which version of WordPress you’re using, some users like to remove the WordPress version number from appearing anywhere in your site’s frontend code.
To do this, you can add the following code snippets to your functions.php file.
function kinsta_hide_version() {
return '';
}
add_filter('the_generator', 'kinsta_hide_version');
Set Up WordPress Pagination
If you’re not happy with how pagination works in your theme, you can use a functions.php code snippet to adjust pagination behavior or even create your own pagination system.
If you’re interested in this type of modification, we have a full guide to WordPress pagination that includes some example functions.php code snippets for you.
Change How Many Results to Include on Search Listing Page
WordPress gives you an in-dashboard option to control how many posts to list on archive pages (Settings → Reading).
However, this changes the number for all archive pages. What if you just want to use a different number for the search results page?
For that, you can add this snippet to your functions.php file – make sure to change the number (“12” in this example) to the actual number of results that you want to display before paginating additional results.
function kinsta_search_results_list() {
if ( is_search() )
set_query_var('posts_per_archive_page', 12);
}
add_filter('pre_get_posts', 'kinsta_search_results_list');
Include Featured Images in the WordPress RSS Feed
If you want to include your posts’ featured images in your RSS feed content, you can add the following snippet to your functions.php file.
function kinsta_featured_image_rss($content) {
global $post;
if ( has_post_thumbnail( $post->ID ) ){
$content = '<div>' . get_the_post_thumbnail( $post->ID, 'full', array( 'style' => 'margin-bottom: 15px;' ) ) . '</div>' . $content;
}
return $content;
}
add_filter('the_excerpt_rss', 'kinsta_featured_image_rss');
add_filter('the_content_feed', 'kinsta_featured_image_rss');
As written, the above code snippet will insert the image at full size. To use a different thumbnail size, you can change “full” to a different thumbnail size – e.g. “large” or “medium”.
Add Upload Support for File Types (E.g. SVG)
By default, WordPress blocks you from uploading certain file types, such as SVG files.
To enable support for these blocked file types, you can add the following code snippet to the WordPress functions.php file:
function kinsta_myme_types($mime_types){
$mime_types['svg'] = 'image/svg+xml';
return $mime_types;
}
add_filter('upload_mimes', 'kinsta_myme_types', 1, 1);
This code snippet only enables SVG uploads, but you can modify it to add support for other file types if needed.
Hide WordPress Update Nags for Non-Administrators
By default, WordPress will show dashboard-wide messages to all users with dashboard access when there’s a new update available.
Even if a user’s role doesn’t allow them to apply the update, the dashboard message will tell that user to contact the administrator.
To adjust this, you can use this code snippet to hide update notifications for all non-Administrator users:
function kinsta_hide_update_nag() {
if ( ! current_user_can( 'update_core' ) ) {
remove_action( 'admin_notices', 'update_nag', 3 );
}
}
add_action('admin_menu','kinsta_hide_update_nag');
For some other variations, check out our guide on how to disable WordPress update notifications.
Change Automatic JPEG Optimization Quality
Though not everyone knows about this feature, WordPress automatically compresses JPEG images when creating thumbnails for your site after you upload images.
Since WordPress 4.5, WordPress has set the default quality level to 82 (with 100 being zero compression).
If you want to make this quality level higher or lower, you can add the following code snippet to your functions.php file – make sure to change the number (“90” in this example) to the actual quality level that you want to use:
add_filter( 'jpeg_quality', create_function( '', 'return 90;' ) );
Best Practices for Organizing Your WordPress functions.php File
If you’re just using the WordPress functions.php file to add a couple of code snippets, you probably don’t need to worry about organization.
But if you’re adding a lot of code snippets to your site, it can quickly get unwieldy and complex if you’re not following some functions.php file organization best practices.
Here are a few best practices to keep your code snippets organized…
Add Code Comments to Explain Everything
When you first add a code snippet to your functions.php file, you know exactly what the snippet does and why you added it. But when you look back at the functions.php file a year later, things might not be so clear.
To avoid this, you’ll want to add code comments to each snippet that explain what the snippet does and why you added it.
Code comments are text that isn’t executed by WordPress, but that human users can read to understand what the code snippet is doing.
To add a single-line code comment, you can use this format:
// This is a single-line code comment
To add a multiple-line code comment, you can use this format:
/**
* This is a code comment that spans multiple lines
* This text is also in the same comment
* This is the last line in the code comment
*/
Here’s an example of how you might use code comments – you can see that the comment before each snippet explains what the snippet does.
Use Include Files to Separate Snippets Into Different Files
If you really have a lot 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 include or require. Mike Schinkel has a good example of how you might do this on StackExchange.
Consider One of the functions.php Alternatives from Above
If you find your functions.php file getting a bit cluttered, you might prefer one of the functions.php alternatives that we detailed earlier.
For example, the free Code Snippets plugin makes it very easy to organize everything because you can add each code snippet separately, complete with its own title and description. You can also use tags to organize your snippets.
Summary
The WordPress functions.php file is a theme-specific file that lets you add PHP code snippets to your website.
If you want to add code snippets to the functions.php file, you should always use a child theme so that your changes don’t get overwritten when you update your theme. We also recommend backing up your site before adding snippets and testing them on a staging site whenever possible.
As an alternative to using the functions.php file, you can also consider a code manager plugin or creating your own custom plugin to house your snippets.
Now that you know how the WordPress functions.php file works, you can start customizing your site in all kinds of helpful ways.
The example functions.php snippets above give you some good places to get started, but the sky’s the limit when it comes to what you can do.
The post WordPress functions.php File: The Ultimate Guide + Helpful Code Snippets appeared first on Kinsta®.
共有 0 条评论