Posts Tagged ‘ functions ’

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

WordPress Cheat

wordpressI know that there are many resources regarding this topic but there are never enough. This post is dedicated to small snippets from WordPress that will make your life easier. Or maybe my life easier and in this case I want to have them in one single post. In a way I’m trying to help you and in another I’m trying to organize this stuff for myself.

Theme Structure

If you want to create a WordPress theme, these following files must be included in order to be a standard theme. You can create a theme using fewer files but this is the way to do it.

1
2
3
4
5
6
7
8
9
10
11
12
header.php - header section
index.php - main section
sidebar.php - sidebar section
footer.php - footer section
single.php - post template
page.php - page template
comments.php - comments template
search.php - search content
searchform.php - search form
archive.php - archive
functions.php - special functions
404.php - error page

The Loop

You will often see “the loop” as reference in many tutorials or samples. This piece of code helps you display your posts on a blog. By entering custom HTML or PHP code inside the loop, you will make every post to benefit from that custom code. You can use the loop mainly in your index.php file but also in other files when you want to display multiple posts.

1
2
3
4
5
6
< ?php if(have_posts()) : ?>
   < ?php while(have_posts()) : the_post(); ?>
// Custom HTML & PHP code
   < ?php endwhile; ?>
< ?php else : ?>
< ?php endif; ?>

Note: the space in front of ?php on the line 1,2,4,5 and 6 should be removed. So instead of < ?php we will have <?php.

Template Include Tags

These tags are usually used in a single PHP file to include other files from the theme. For example you can use the get_header tag in index.php in order to include the head in the theme.

1
2
3
4
< ?php get_header(); ?>
< ?php get_sidebar(); ?>
< ?php get_footer(); ?>
< ?php comments_template(); ?>

Template Bloginfo Tags

These tags are used to display information regarding your blog, information that can be customized inside the WordPress Administration panel.

1
2
3
4
5
6
7
8
9
10
< ?php bloginfo('name'); ?> - Title of the blog
< ?php bloginfo('charset'); ?> - Displays the character set
< ?php bloginfo('description'); ?> - Displays the description of the blog
< ?php bloginfo('url'); ?> - Displays the address of the blog
< ?php bloginfo('rss2_url'); ?> - Displays the RSS URL
< ?php bloginfo('template_url'); ?> - Displays the URL of the template
< ?php bloginfo('pingback_url'); ?> - Displays the pingback URL
< ?php bloginfo('stylesheet_url'); ?> - Displays the URL for the template's CSS file
< ?php bloginfo('wpurl'); ?> - Displays URL for WordPress installation
< ?php bloginfo('name'); ?>

WordPress Conditional Tags

Conditional tags are simple but helpful tags that can be used to customize how your blog will work. For example if the page is the home page, we will type a class called “current-cat”. < ?php if(is_home()) { ?> class=”current-cat”< ?php } ?>. This is a part of the code which I will present you a little bit later in this article.

1
2
3
4
5
6
is_home() - when the user is on the home page(blog)
is_front_page() - when the user is on the home page (blog or page)
is_single - when a single post is displayed
is_sticky() - check if a post is sticky
is_page() - when a page is displayed
is_category() - when a category is displayed

These are the most common conditional tags inside WordPress. For more information and additional tags you can check the next address dedicated to conditional tags. http://codex.wordpress.org/Conditional_Tags

Common WordPress Tags

As you know WordPress has a lot of code that can be embedded in themes in order to make them complex and powerful. Here are some of the common snippets that are used in most of the templates.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
< ?php the_time() ?> - Displays the time of the current post
< ?php the_date() ?> - Displays the date of a post or set of posts
< ?php the_title(); ?> - Displays or returns the title of the current post
< ?php the_permalink() ?> - Displays the URL for the permalink
< ?php the_category() ?> - Displays the category of a post
< ?php the_author(); ?> - Displays the author of the post
< ?php the_ID(); ?> - Displays the numeric ID of the current post
< ?php wp_list_pages(); ?> - Displays all the pages
< ?php wp_tag_cloud(); ?> - Displays a tag cloud
< ?php wp_list_cats(); ?> - Displays the categories
< ?php get_calendar(); ?> - Displays the calendar
< ?php wp_get_archives() ?> - Displays a date-based archives list
< ?php posts_nav_link(); ?> - Displays Previous page and Next Page links
< ?php next_post_link() ?> - Displays Newer Posts link
< ?php previous_post_link() ?> - Displays previous link

WordPress Navigation Menu

This thing is different based on how you want your blog to work. You can have a menu based on pages, on categories or on both. In every way you will need a home page link. In this case here the the 2 approaches for the menu.

Categories based menu

1
2
3
4
5
<ul id="menu">
<li <?php if(is_home()) { ?>< ?php } ?>>
<a href="<?php bloginfo('home'); ?>">Home</a></li>
< ?php wp_list_categories('title_li=&orderby=id'); ?>
</ul>

Pages based menu

1
2
3
4
5
<ul id="menu">
<li <?php if(is_home()) { ?>< ?php } ?>>
<a href="<?php bloginfo('home'); ?>">home</a></li>
< ?php wp_list_pages('sort_column=menu_order&depth=1&title_li='); ?>
</ul>

In both cases we add a class that is used by WordPress in styling the list items. So, in this case we will add the classes to a hardcoded home list item.

Display X posts from a category

On the first page we have in the sidebar 2 sections for latest tips and latest graphic ratings. Those sections were made with the help of the query_posts.

1
< ?php query_posts('category_name=Name Here&showposts=10'); ?>

The name should be exactly the same as the one typed in the Administration panel under categories section.

Custom Template File

In WordPress you can insert any additional template file that is none of the ones in the first section. In this way you can make your own template file and embed it in your theme.

1
< ?php include (TEMPLATEPATH . '/searchform.php'); ?>

Final words
This is WordPress Cheat Sheet. For more information, you can search the WordPress Codex. You can find there all the information you need: tags, parameters, functions, hacks etc. Hopefully this page will help you and it will give you a little more time in designing instead of researching. Thanks WordPress and cheers!