Adding WordPress Functions

This is a tutorial for WordPress developers, theme developers and aspiring WordPress gurus. I would consider this an intermediate level tutorial. The concepts are a little complex, but very easy to implement. I will show you several useful WordPress functions that can be added to your current theme’s functions.php file to enhance the look and functionality of your WordPress website or blog. I will also demonstrate how, through the use of hooks, you can call upon those functions when certain events occur. I will also explain how to apply functions that filter text before it is displayed to the screen.

Prerequisites

There are some things you need to understand somewhat before attempting to use this tutorial, but if you don’t know everything, don’t worry, this is not a hard tutorial to follow. You can get by with only limited knowledge of PHP and the WordPress infrastructure because I will explain things in a step by step manner. It always helps to have as much knowledge of PHP, HTML, JavaScript and WordPress whenever working with the WordPress core however. So no matter how advanced you are on these techniques, give it a shot. Often times the best way to learn is do so by just doing it. That is how I first learned how do code many years ago and today I am able to code in over a dozen languages.

The Functions.php File

There is a functions.php file in every WordPress theme that I have worked with. It is the commonly used file for adding PHP functions to WordPress themes. It effectively hooks into the WordPress core and adds the desired functionality to your entire site, making a function available for use on any post or page. There are two ways to find your functions.php file. I like to use a FTP application such as FileZilla, but you can also access them directly through the WordPress admin. To locate your functions.php file with an FTP client, navigate to your server’s root directory then go to /wp_content/themes and look for a directory named after the theme you are using. In the WordPress admin, simply open the editor and select your theme from the drop down in the top right of the page. Then look in the left column for the functions.php file and click on it to bring it up in the editor.

Filters and Actions

Functions are commonly called in WordPress by using actions or filters. Actions are hooks WordPress call upon when specific events occur. For example you may want a custom function to be called when publishing a post or showing a page.

Filters are hooks that call upon functions used to modify text. They are either applied to the text before it is saved to a database table or before it is sent to the screen for viewing.

I found a decent reference for filters in the WordPress codex at:
http://codex.wordpress.org/Plugin_API/Filter_Reference

There is also a list of actions in the codex at:
http://codex.wordpress.org/Plugin_API/Action_Reference

Adding a Function to WordPress

Adding a simple function to WordPress is done by editing the functions.php file. I generally like to add them towards the top of the page, but you can add them where ever you like except of course inside of an existing function. The start or end of the functions.php file are the most practical places to add your functions. Be sure to place a comment before your function so you will know what it does in the future. Also make your comments concise so the others who may end up editing the file will know what it was added for. It is also a good idea to explain any parameters in the comments before a function. Single line comments are added using two forward slashes before the text. Multiple line comments are added using slashes and asterisks as in the following example:

Function for Changing Excerpt Length

<?php
/*
set_excerpt_length function:
 Written by: Ian L. of Jafty.com 
Purpose: changes the length of post excerpts.
*/
function set_excerpt_length($length=70) {
	//the number of words in each excerpt:
	return $length;
}
add_filter( 'excerpt_length', 'set_excerpt_length');
?>

Notice the use of both comment types in the above PHP code as well as the add_filter call after the function to hook it into the WordPress core. The above functions makes use of the excerpt_length filter to change the length of post excerpts on your WordPress blog. The excerpt_length filter is just one example of a collection of hooks. In the above set_excerpt_length function, I set the default length to 70 words by setting the variable, $length to 70 in the functions parenthesis. You can change the value by setting the length when calling the function within the add_filter call as well. For example, if you wanted to set the length to 20 words instead, you would change the add_filter line to read:

add_filter( ‘excerpt_length’, ‘set_excerpt_length(20)’);

Calling a Function on Page Load

The following function demonstrates how you might add some code to the header of each page in WordPress. By using the wp_head action, WordPress calls the function you specify every time a new page is opened.

 <?php
function say_hi($toName){
echo "<script>alert('Hello $toName! Welcome to my WordPress blog...');</script>";
}
add_action('wp_head', 'say_hi');
?>

The function above simply calls the say_hi function when the page loads by adding a JavaScript alert dynamically with PHP in the header of any page that is visited. Obviously that means it will be called anytime any page is opened, so you may want to add more code to the function to limit it to the home page. This is just an example function however. You could use this technique to add something that is more suited to be called into action when any page loads.

Filtering Comment Text Function

This I a handy function to get rid of any unwanted words in comments on a WordPress site. You can use it to filter out foul language or any other words you just don’t want to show up on your blog.

function filter_bad_text($content) {
	$badwords = array('arse','hell','freelancer');
  $content=str_ireplace($badwords,'{censored for content}',$content);
  return $content;
}
add_filter('comment_text', 'filter_bad_text');

If you notice, I used the comment_text filter hook. The coment_text filter hook is applied to comment text before it is presented to the screen so that any words in the badwords array will no longer show up. They will be replaced with {censored for content} instead. You can change the replace text with whatever you wish as well.

Creating an Action Hook

If you don’t see the action hook you need to accomplish your goal, you can add an action hook with the do_action function. For example, if you wanted to add an action to the index.php page that triggers just before the post loop that prints posts to the page. Look for the loop in index.php which starts with a line similar to the following line of code:

if (have_posts()) : while (have_posts()) : the_post();

Then add the following line of code just above it:

do_action( ‘before_post_loop’ );

That effectively adds a new action hook named ‘before_post_loop’ to WordPress and it can be called upon simply by using:

add_action(‘before_post_loop’, ‘some_function’);

Notice the parameters. The add_action function takes the action name we created followed by a function that you want to apply before the WordPress loop is called. In this case, the function you name in place of “some_function” will get called in index.php before the posts are displayed.

Summary

After reading this tutorial, you should have a good idea of how to make use of many of the action and filter hooks in the WordPress codex. You should also be able to add your own filter and action hooks which gives you the freedom to alter the look and functionality of your WordPress site in numerous ways. Good luck using hooks and PHP functions in your own WordPress environment and have fun adding useful functionalities to your blog or website. The possibilities are endless.

One thought on “Adding WordPress Functions

  1. Rather than adding it to the theme’s functions.php file, using a plugin like Code Snippets may be a better idea.

    Why?

    Because if you switch themes then you have to track down any of actions or filters that you added and want to keep and then add them to the new theme’s functions.php file. Also, there is some risk of losing it during a theme update. Using the Code Snippets plugin makes them update safe as well as providing an easy to use management interface for adding/removing snippets.

    I’m not affiliated with the plugin in anyway, just a user.

Comments are closed.