WordPress functions.php Tutorial
When designing WordPress Themes, you might have wanted to customize a theme by adding your own set of functions to make it come closer to your wants and needs.
You are not the only one, and the funny thing is, some of the functions you want to add, are also the ones I (or someone else out there in the programming world) want to add. We can very easily do that by using the functions.php
file.
What exactly is this file?
There might be some of you who don’t have even the minimal idea of what functions.php
is. It actually is a template used by WordPress Themes, called also a “theme functions file” which acts like a plug-in and is automatically executed by both the admin and the front-end pages of a WordPress site. In most cases it is used to extend the functionality of a WordPress installation or theme, define functions, filters, classes and actions that are to be used by other templates in the said theme.
Every WordPress theme has it’s own functions.php
file, which can be found in your themes folder. You can go from there to add your own touch by modifying it, and adding both built-in WordPress functions and regular PHP ones to hooks and filters that are predefined.
In most cases you will have more than one theme installed, and probably all of them will have their own functions.php
file. What happens then? By making an educated guess, we say that only the activated theme’s file will be executed, and we would be very accurate. There are cases (very few) when the theme you’re working on doesn’t even have this file. Do not worry, you can just create one yourself the usual old-fashioned way and add it into your theme’s directory.
And if you are using a child theme? Child themes may have their own functions.php
file, which can contain additional functions of the parent theme’s one, or even new functions that partially or completely overrule them. So why is this file called functions.php
and not a Plug-In? Let’s explain!
Plug-In VS functions.php
If functions.php
works mostly as a plug-in, then why isn’t it called one, but a file instead? Because they have some very subtle, but substantial differences. These are:
Headers
While a WordPress plug-in requires specific Header text, functions.php
does not.
Location
By now, you know that the functions file is stored in the wp-content/themes
directory. Similarly, plug-ins are stored in the wp-content/plugins
directory.
Execution
While you have to activate every WordPress plug-in separately for it to be executed, the functions file is executed only with the activation of the theme it is placed into.
Field of effect
While plug-ins are applied to all the themes you have installed, the functions file loses it’s field of effect once the theme it’s in is deactivated.
Purpose
While the functions.php
file can be used to add multiple features and functions to a site, plug-ins are more focused and only have one purpose for which they are used.
You might be asking yourself: What are those functions we wanted to add here anyway? Let’s get to the point!
Most used and Most Necessary Functions in your functions.php file
There are arguably no limits to what you can achieve with properly modifying your functions.php
file, that being adding Google Analytics, FavIcons, custom Navigation Menus or removing the WordPress version number, default Author Profile’s fields and many others. We’ll explain below!
1. Adding Google Analytics
Google Analytics is a very much needed tool, as you can gather important data on the visitors of your site, such as how many people visit it and when, what pages do they spend more time on, how much time do they spend there, and also other data such as where where they are when accessing your site, how did they access it and also how they interact with your site. As you can see, pretty important for you to create and modify a strategy on how to improve everything.
If by now you want to use it then let’s get you to it. First you have to sign up for a Google Analytics account using you Gmail address (make sure you have a Gmail address, because you will not be able to register without one). You will then be given the choice between a website and a mobile app, and you should make sure to choose the website option. After this you will be required to give some information such as your site’s name, URL and similar important and self-explanatory stuff. Then you click the Get Tracking ID button, agree to the terms and conditions, and you’re prompted to your tracking code. Easy peasy, right? Copy that code!
We’ve only talked about Google Analytics until now, but not how to add it into your site. What you have to do is paste the code below into your functions.php file
:
<?php add_action('wp_footer', 'add_googleanalytics'); function add_googleanalytics() { ?> // Paste your Google Analytics code here <?php } ?>
It’s this easy! The code should look something like this UA-61604166-1
.
2. Removing WordPress Version Number
The best way to avoid this problem entirely is to just upgrade to the latest version of WordPress! It would save us all the time and effort to do any modifications to the version’s number!
But just in case you are working with a client that is stubborn and does not agree to upgrading, then you need to remove the version number. That can be done by adding the code below to your functions file:
function website_remove_version() { return ''; } add_filter('the_generator', 'website_remove_version');
Or, you know, convince them to upgrade! It’s for the greater good!
3. Customizing the Dashboard logo
If you want to enjoy working on your site while having your working space (dashboard) completely personalized, then you can change the dashboard logo to something more creative and inspiring! Or, if your client is being annoying, you can change it to something dull for them, that’s perfectly good revenge!
You can do that by adding the code snippet below:
add_action('admin_head', 'my_custom_logo'); function my_custom_logo() { echo ' #header-logo { background-image: url('.get_bloginfo('template_directory').'/images/custom-logo.gif) !important; } '; }
But probably you shouldn’t annoy your annoying client, just in case.
4. Adding a Favicon to your blog
You might have noticed the small logo that stands before the URL in the URL bar by now. That mini-picture is called a favicon, and you can use your very own for your website. First of all you should know that the pic should be of a certain size (usually 16×16 or 48×48) and format (.ico). To make your own favicon you can just make a logo (or take a picture) and use a favicon generator to make it into a favicon with all the requirements for a picture to be one.
Then you add this code into your functions.php
file:
function blog_favicon() { echo ''; } add_action('wp_head', 'blog_favicon');
After this simple action you will have added to your blog’s own identity, to make it stand out from all the others in the wide wide web.
5. Adding Author Profile fields
Sometimes you might feel the need to add your custom contact fields for your authors, or even other stuff that are not there by default. You can very easily do this by adding the function below into your file:
function my_new_contactmethods( $contactmethods ) { // Add Twitter $contactmethods['twitter'] = 'Twitter'; //add Facebook $contactmethods['facebook'] = 'Facebook'; return $contactmethods; } add_filter('user_contactmethods','my_new_contactmethods',10,1);
Even though we used the function to add contact fields for Twitter and Facebook, you can use it for whatever comes to mind.
6. Customizing the footer
As your theme might have a long and elaborate footer with lots of links and other acknowledgements to people who helped make said theme, you will want to make it into something simpler and classier. Or it might be the reverse, having to give some shine to an otherwise boring and short footer, but let’s go for the first one on this (because I like it so, and will yield on something else later on).
What you will have to do is add this code into your functions file:
function remove_footer_admin () { echo 'Lovingly by WebCodeGeeks'; } add_filter('admin_footer_text', 'remove_footer_admin');
Note that all you want to be visible in the footer will go inside echo '//here';
. As you see, it will need to be written in HTML format for you to add it the style you want.
7. Dynamic Copyright date
Sometimes, we see websites that have an outdated copyright date because they might have forgotten to change it, or you see it before they do, or sometimes they even just put the current year as the copyright date. Of course, you don’t want this to happen to your website. To avoid it, you can use the functions.php
file.
You include the code below in it:
function updated_copyright() { global $wpdb; $copyright_dates = $wpdb->get_results(" SELECT YEAR(min(post_date_gmt)) AS firstdate, YEAR(max(post_date_gmt)) AS lastdate FROM $wpdb->posts WHERE post_status = 'publish' "); $output = ''; if($copyright_dates) { $copyright = "© " . $copyright_dates[0]->firstdate; if($copyright_dates[0]->firstdate != $copyright_dates[0]->lastdate) { $copyright .= '-' . $copyright_dates[0]->lastdate; } $output = $copyright; } return $output; }
What we have done here is retrieving the date of the first and last post, and then use them to display the years of the copyright date like this: © 2010 – 2015. After you add this code to the functions.php
file, you go to footer.php
and place this code snippet wherever you want it to be displayed:
<?php echo updated_copyright(); ?>
Now you have a dynamic and correct copyright date.
8. Eliminate jumping for the “read more”
There are some very annoying websites that take you halfway down a page when you click the link that takes you to it. Now, normally, if the jump was made within the same page it would make sense, but not if it is a whole another website. You can avoid this thing happening to your website by adding this code to your functions file:
function no_more_jumping($post) { return 'ID).'" class="read-more">'.'Continue Reading'.''; } add_filter('excerpt_more', 'no_more_jumping'); add_filter('the_content_more_link', 'remove_more_jump_link');
Even though just by doing this you can have your new functionality, note that this is a good place to customize your tag.
9. Remove the reminder for WordPress Update
If you are like those clients we mentioned above that don’t like updating your WordPress version (or be advised for it, more like it), then those sweet little messages reminding you to do so every time there is an update, may not look so sweet to you. Good news! There’s a way to get rid of them!
All you have to do is add the code snippet below into your functions file:
if (!current_user_can('edit_users')) { add_action('init', create_function('$a', "remove_action('init', 'wp_version_check');"), 2); add_filter('pre_option_update_core', create_function('$a', "return null;")); }
There, you’re free of nagging now! However, if that nag is what you rely on to be aware of new updates, you can always comment this one out.
10. Custom excerpt length
If you think the default 55-words limit for the excerpts of your posts is too long (or too short), you can always change it, using the code below:
function custom_excerpt_length($length) { return 30; } add_filter('excerpt_length', 'custom_excerpt_length');
You can change the 30
into whatever length you want your excerpts to be.
11. Enabling threaded comments
The first time I saw threaded comments in usage, I was thoroughly amazed. And the last time I visited a favorite blog which didn’t have this, I got so annoyed at having to check all the comments section to find where had people responded to an interesting comment that I nearly gave up searching. So I had to send an email to the bloggers to please, for the love of God, use threaded comments.
If you don’t want to be on the receiving end of such emails, you can add this snippet in your functions.php
file, and be done with it:
function enable_threaded_comments(){ if (!is_admin()) { if (is_singular() AND comments_open() AND (get_option('thread_comments') == 1)) wp_enqueue_script('comment-reply'); } } add_action('get_header', 'enable_threaded_comments');
Apparently they saw my email, and now I can read comments in peace!
12. Another way of including jQuery
While most of us may be very comfortable with including jQuery in the head section, you might want to know that there is another simple way of doing so. You add this code snippet into your functions file:
if (!is_admin()) { wp_deregister_script('jquery'); wp_register_script('jquery', ("https://www.webcodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9hamF4Lmdvb2dsZWFwaXMuY29tL2FqYXgvlibs/jquery/1/jquery.min.js"), false); wp_enqueue_script('jquery'); }
But what are the advantages of using this? It makes sure that there is only one copy of jQuery included and saves some bandwidth by just calling it directly from Google’s servers and also taking a bit of advantage of any primed caches that are visiting. However, there’s a small catch: You have to place this function before the one we explained above on the threaded comments, otherwise it won’t work.
You can add lots and lots of other functions, depending on what you think is useful and necessary for your website.
Download the source code
This was an example of functions.php in WordPress.
Download the source code for this tutorial:
You can download the full source code of this example here : Functions.php