WordPress functions.php Template with 15 Essential Custom Functions

When designing WordPress themes, I always add a common set of custom functions to the theme’s functions.php file. This speeds up development time because I don’t have to hunt for and individually copy the same slew of functions for every theme. I just drop in a copy of my functions.php template and build up from there. This takes care of all those little things that always need to be done:

  • Include jQuery
  • Enable threaded comments
  • Add feed links to the header
  • Disable unused widget areas
  • Adding Google Analytics to the footer
  • Stop the “Read More” link from jumping to the middle of the next page ;)

One of the things that I like about these functions is that they’re all so concise, simple, and effective. The functions.php template file currently contains 15 different functions and is a continual work in progress. Not everyone is going to need or use everything in the file, but the idea is to modify this template into something that works for you. It’s a starting point with some really useful functions.

In this DiW article, we first provide an explanation of each of the 15 functions and then bring them all together into the working functions.php template. Just copy and paste the template code at the end of this article or grab a copy of the zipped functions.php file and enjoy a custom collection of functions that will help you optimize your development process while enhancing WordPress with essential functionality.

Add feed links to header

Since version 2.8, WordPress can add all relevant feed links (main, comments, categories, et al) to your <head> area. It doesn’t happen by default, however, because you have to add the following snippet to make it work:

// add feed links to header
if (function_exists('automatic_feed_links')) {
	automatic_feed_links();
} else {
	return;
}

This will check to see if you’re using a version of WordPress that is compatible, and then enable the automatic feed links. A couple of notes: first, this method assumes that you are not manually including any feed links in your <head>. Also, I read a recent Trac ticket that looked like this functionality was being integrated with add_theme_support, so keep your eyes open for that.

Automatic jQuery inclusion

We’ve discussed how to include jQuery the right way by placing a little snippet in your document head, but here is a way to do it from your theme’s functions.php file:

// smart jquery inclusion
if (!is_admin()) {
	wp_deregister_script('jquery');
	wp_register_script('jquery', ("http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"), false);
	wp_enqueue_script('jquery');
}

This code ensures that only one copy of jQuery is included, and calls it from Google’s servers to save bandwidth and take advantage of any primed caches that happen to be visiting. Note that this function needs to be located before the threaded-comments function in order for it to work.

Enable threaded comments

As we explain in the book, enabling threaded comments requires adding a snippet of code into your <head> area just before the wp_head tag. After a little experimenting, I discovered that you can include this snippet from the functions.php file:

// enable threaded comments
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');

This helps keep your document <head> a little cleaner. Note that this function needs to be located after the jQuery-inclusion function in order for it to work.

Remove unwanted crap from the head section

As we’ve mentioned before, WordPress spits out a ton of crap in the document <head> – stuff like the version number and WLW, RSD, and index links. To clean things up, we add this nice little snippet into the functions.php template:

// remove junk from head
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wp_generator');
remove_action('wp_head', 'feed_links', 2);
remove_action('wp_head', 'index_rel_link');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'feed_links_extra', 3);
remove_action('wp_head', 'start_post_rel_link', 10, 0);
remove_action('wp_head', 'parent_post_rel_link', 10, 0);
remove_action('wp_head', 'adjacent_posts_rel_link', 10, 0);

Add Google Analytics to the footer

Another annoying task that has to be done for all of the sites I create is adding Google Analytics code to the footer.php file. Recently it occurred to me to just add the code to my functions.php and never worry about it again:

// add google analytics to footer
function add_google_analytics() {
	echo '<script src="http://www.google-analytics.com/ga.js" type="text/javascript"></script>';
	echo '<script type="text/javascript">';
	echo 'var pageTracker = _gat._getTracker("UA-XXXXX-X");';
	echo 'pageTracker._trackPageview();';
	echo '</script>';
}
add_action('wp_footer', 'add_google_analytics');

A couple of notes here: first, obviously you want to replace the “UA-123456-1” with your actual GA code. Second, you may want to check out the three currently available Analytics options and modify the code accordingly. Currently, this function is using the newer “ga.js” tracking code, but that is easily changed to either of the other methods.

Custom excerpt length

Instead of using the default 55-word limit, this function enables you to specify any length for your excerpts.

// custom excerpt length
function custom_excerpt_length($length) {
	return 20;
}
add_filter('excerpt_length', 'custom_excerpt_length');

Just set your preferred number of words by editing the “20” to whatever you wish.

Custom excerpt “continue” string

Or whatever they call that funky bracketed ellipses thing “[...]” that is appended to your post excerpts by default. I like to remove the brackets, but with this functions.php snippet you can change it to anything:

// custom excerpt ellipses for 2.9+
function custom_excerpt_more($more) {
	return '...';
}
add_filter('excerpt_more', 'custom_excerpt_more');

/* custom excerpt ellipses for 2.8-
function custom_excerpt_more($excerpt) {
	return str_replace('[...]', '...', $excerpt);
}
add_filter('wp_trim_excerpt', 'custom_excerpt_more'); 
*/

As you can see, there are two different versions of this code, depending on your version of WordPress. We like to stay current, so we commented out the older method but left it there in case you need it. For either version of this technique, just replace the “...” with “pants on the ground” or whatever happens to suit your needs.

No “more” jumping for the “read more” link

One of the weirdest things that WordPress does is “jump” the reader to the location of the “<!--more-->” tag on the single-post-view when the “read more” link is clicked. It’s just awkward — if the jump was on the same page, it would make sense, but to load a new page and then take the reader halfway down without explaining anything is just wrong. In any case, here is a nice little function that will stop the jumping once and for all:

// no more jumping for read more link
function no_more_jumping($post) {
	return '<a href="'.get_permalink($post->ID).'" class="read-more">'.'Continue Reading'.'</a>';
}
add_filter('excerpt_more', 'no_more_jumping');

Nothing else needs to be done for this to work – just plug it in and enjoy your new “jumpless” functionality. Note that this is also a convenient place to customize the “read more” link with whatever attributes or custom text you wish.

Add a favicon to your blog

You just gotsta have a favicon for your blog, and this code makes it super easy to do. Just create your image and upload to site’s root directory. The following code in your functions.php file makes it so by adding the required line to your <head> area:

// add a favicon to your 
function blog_favicon() {
	echo '<link rel="Shortcut Icon" type="image/x-icon" href="'.get_bloginfo('wpurl').'/favicon.ico" />';
}
add_action('wp_head', 'blog_favicon');

Feel free to change the directory to whatever you desire. Also make sure that the wp_head is present within your theme’s header.php file.

Add a different favicon for your blog’s Admin area

While we’re here, let’s add a unique favicon to our Admin pages, so that they are easier to recognize when bookmarked or working with tabs. Just create a favicon and upload to your theme’s /images/ directory. This code takes care of the rest:

// add a favicon for your admin
function admin_favicon() {
	echo '<link rel="Shortcut Icon" type="image/x-icon" href="'.get_bloginfo('stylesheet_directory').'/images/favicon.png" />';
}
add_action('admin_head', 'admin_favicon');

As before, feel free to change the directory to whatever you desire. It might be best to keep your admin favicon in a separate directory than your blog favicon. Just sayin’.

Custom Admin Login logo

You know that snazzy blue WordPress logo that is branding your various login pages? Yeh, you can change that to whatever you want. Just create your custom login image, name it “custom-login-logo.png”, and upload it to your theme’s /images/ directory. This code will take care of the rest:

// custom admin login logo
function custom_login_logo() {
	echo '<style type="text/css">
	h1 a { background-image: url('.get_bloginfo('template_directory').'/images/custom-login-logo.png) !important; }
	</style>';
}
add_action('login_head', 'custom_login_logo');

The key here is to make sure that the path and image names match that of your setup. Also, when creating your image, you may want to keep in mind the properties of the original: 30px length, 31px height, transparent GIF format, and header background color of #464646 (for the image matte).

Disable unused widget areas

Justin Tadlock shares this handy function for removing unwanted widget areas from our theme – a must for customizing existing themes:

// disable all widget areas
function disable_all_widgets($sidebars_widgets) {
	//if (is_home())
		$sidebars_widgets = array(false);
	return $sidebars_widgets;
}
add_filter('sidebars_widgets', 'disable_all_widgets');

This code is plug-&-play – no other modifications need to be made. Note: if you only want to disable widgets on your Home page, then remove the two comment slashes (“//”) from the third line.

Kill the WordPress update nag

This is one of my favorites, but I know it’s not for everyone. In any case, you know that “Please update now..” message that appears on every page in the WordPress Admin when new versions are available? This sweet little function kills it dead (or disables it, actually):

// kill the admin nag
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;"));
}

Feel free to comment this one out or remove it if you rely on the Admin nag to keep you informed of changes.

Include category ID in body_class and post_class

By default, WordPress body_class and post_class do not include the ID of the category of the current post. This custom function changes all that:

// category id in body and post class
function category_id_class($classes) {
	global $post;
	foreach((get_the_category($post->ID)) as $category)
		$classes [] = 'cat-' . $category->cat_ID . '-id';
		return $classes;
}
add_filter('post_class', 'category_id_class');
add_filter('body_class', 'category_id_class');

Even if you aren’t using it, it’s a nice function to have around, which is why it’s included here for this custom functions.php template of essential functions. Keywords in the house because we can.

Get the first category ID

Another useful function when working with different categories is the ability to get the first category ID of the current post. This function makes it happen:

// get the first category id
function get_first_category_ID() {
	$category = get_the_category();
	return $category[0]->cat_ID;
}

Strictly plug-&-play: just use <?php get_first_category_ID(); ?> in your theme template file to access the data.

Putting it all together..

As promised, here is the full-meal deal – the entire collection neatly organized into a single chunk of code:

<?php // custom functions.php template @ digwp.com

// add feed links to header
if (function_exists('automatic_feed_links')) {
	automatic_feed_links();
} else {
	return;
}


// smart jquery inclusion
if (!is_admin()) {
	wp_deregister_script('jquery');
	wp_register_script('jquery', ("http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"), false, '1.3.2');
	wp_enqueue_script('jquery');
}


// enable threaded comments
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');


// remove junk from head
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wp_generator');
remove_action('wp_head', 'feed_links', 2);
remove_action('wp_head', 'index_rel_link');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'feed_links_extra', 3);
remove_action('wp_head', 'start_post_rel_link', 10, 0);
remove_action('wp_head', 'parent_post_rel_link', 10, 0);
remove_action('wp_head', 'adjacent_posts_rel_link', 10, 0);


// add google analytics to footer
function add_google_analytics() {
	echo '<script src="http://www.google-analytics.com/ga.js" type="text/javascript"></script>';
	echo '<script type="text/javascript">';
	echo 'var pageTracker = _gat._getTracker("UA-XXXXX-X");';
	echo 'pageTracker._trackPageview();';
	echo '</script>';
}
add_action('wp_footer', 'add_google_analytics');


// custom excerpt length
function custom_excerpt_length($length) {
	return 20;
}
add_filter('excerpt_length', 'custom_excerpt_length');


// custom excerpt ellipses for 2.9+
function custom_excerpt_more($more) {
	return '...';
}
add_filter('excerpt_more', 'custom_excerpt_more');

/* custom excerpt ellipses for 2.8-
function custom_excerpt_more($excerpt) {
	return str_replace('[...]', '...', $excerpt);
}
add_filter('wp_trim_excerpt', 'custom_excerpt_more'); 
*/


// no more jumping for read more link
function no_more_jumping($post) {
	return '<a href="'.get_permalink($post->ID).'" class="read-more">'.'Continue Reading'.'</a>';
}
add_filter('excerpt_more', 'no_more_jumping');


// add a favicon to your 
function blog_favicon() {
	echo '<link rel="Shortcut Icon" type="image/x-icon" href="'.get_bloginfo('wpurl').'/favicon.ico" />';
}
add_action('wp_head', 'blog_favicon');


// add a favicon for your admin
function admin_favicon() {
	echo '<link rel="Shortcut Icon" type="image/x-icon" href="'.get_bloginfo('stylesheet_directory').'/images/favicon.png" />';
}
add_action('admin_head', 'admin_favicon');


// custom admin login logo
function custom_login_logo() {
	echo '<style type="text/css">

	h1 a { background-image: url('.get_bloginfo('template_directory').'/images/custom-login-logo.png) !important; }
	</style>';
}
add_action('login_head', 'custom_login_logo');


// disable all widget areas
function disable_all_widgets($sidebars_widgets) {
	//if (is_home())
		$sidebars_widgets = array(false);
	return $sidebars_widgets;
}
add_filter('sidebars_widgets', 'disable_all_widgets');


// kill the admin nag
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;"));
}


// category id in body and post class
function category_id_class($classes) {
	global $post;
	foreach((get_the_category($post->ID)) as $category)
		$classes [] = 'cat-' . $category->cat_ID . '-id';
		return $classes;
}
add_filter('post_class', 'category_id_class');
add_filter('body_class', 'category_id_class');


// get the first category id
function get_first_category_ID() {
	$category = get_the_category();
	return $category[0]->cat_ID;
}

?>

Download the custom functions.php template file

If you prefer, you can download this code in a ready-to-go functions.php file in zipped format:

Download zipped functions.php Template File

Source:

Digging into wordpress

  1. nice inpoh gan..
    i`ll try with u`r way
    thx

    • hoscarzv
    • June 26th, 2010

    good work. thanks for sharing.

    • Salal
    • August 17th, 2010

    Thanks for the information……

    • things that cheer me up
    • October 9th, 2010

    thanx! this post is great! I’m a beginner and this might be a stupid question to you but could you please tell me where can I find the footer.php file? I’m trying to make google analytics to work but don’t seem to have any luck so far. Could you please explain furthur? Thanks again!

    • kathir
    • October 9th, 2010

    why to create function.php file?

  2. Hiya! Quick question that’s completely off topic. Do you know how to make your site mobile friendly? My web site looks weird when browsing from my apple iphone. I’m trying to find a template or plugin that might be able to correct this problem. If you have any recommendations, please share. With thanks!

  3. What’s up, yeah this paragraph is in fact nice and I have learned lot of things from it on the topic of blogging. thanks.

  4. Thanks for the auspicious writeup. It in reality was a leisure account it. Look complex to far added agreeable from you! By the way, how could we keep in touch?

  5. advertising

  6. Hey there, my name’s Cheryl and sometimes I write about the same thing on my blog. I actually do have some questions for you if you don’t mind.
    Is it just me or does it seem as if a bunch of the responses seem like they are coming
    from brain dead people? :-P Also, if you happen to be on other social network sites like web 2.
    0 site list, I’d like to keep in touch. Is it possible you could post a list of all of your shared sites like your Twitter, Facebook page or linkedin profile?

  7. I understand this is kind of off topic but I was curious if you knew
    where I could possibly acquire a captcha plugin for my feedback form?
    I’m using the same blog platform as yours and I’m having trouble
    locating one?

  8. Hello, i feel that i saw you visited my blog thus
    i came to go back the choose?.I am trying to find things to improve
    my site!I guess its good enough to use a few of your ideas!

    !

  9. It’s very simple to find out any topic on web as compared to textbooks, as I found this post at this website.

  10. Hey! Do you know if they make any plugins to protect against hackers?
    I’m kinda paranoid about losing everything I’ve worked hard
    on. Any recommendations?

  11. Quality articles is the main to be a focus for the
    visitors to pay a quick visit the web site, that’s what this web page is providing.

  12. My brother suggested I might like this web site. He was totally right.

    This post truly made my day. You cann’t imagine simply how much time I had spent for this info! Thanks!

  13. This piece of writing is actually a pleasant one it assists new web viewers, who are wishing
    in favor of blogging.

  14. Thank you for every other excellent post. Where else could anyone get that type of info in such
    an ideal approach of writing? I have a presentation next week, and
    I am at the search for such information.

  15. Hi there to every body, it’s my first visit of this blog; this web site contains awesome and genuinely good information for visitors.

  16. This is the right web site for anyone who really wants to find
    out about this topic. You know a whole lot its almost hard
    to argue with you (not that I personally would want to…HaHa).
    You definitely put a fresh spin on a subject that has been discussed for decades.
    Excellent stuff, just great!

  17. I think all your tips are wonderful! Split up and also
    list it down. This always looks better and also more understandable when you write
    your points like that. Thanks for the tips!
    Cheers!

  18. You have a few useful tips! Perhaps I would think of performing this on my own.
    Very much appreciated!

  19. Thank you a bunch for sharing this with all folks you actually
    realize what you’re speaking about! Bookmarked. Please additionally visit my site =). We will have a link alternate arrangement among us

  20. I agree with preceding poster, seems to be like you will do properly out right here
    around the world-wide-web. Cheers!

  21. Greetings from Colorado! I’m bored to tears at work so I decided to
    browse your site on my iphone during lunch break. I love the knowledge you present here and can’t wait to take a look
    when I get home. I’m surprised at how fast your blog loaded on my cell phone ..
    I’m not even using WIFI, just 3G .. Anyways, great site!

  22. Simply want to say your article is as astounding.
    The clarity in your post is just great and i could assume you are an expert
    on this subject. Fine with your permission let me to grab your feed to keep up
    to date with forthcoming post. Thanks a million and please keep up the gratifying
    work.

  1. January 8th, 2011
    Trackback from : 2010 in review « MalarVizhi

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 204 other followers

%d bloggers like this: