Using a Functions file

You may have used a theme in the past, or are currently using one, that has a functions.php file in it. The Theme Functions file was introduced around the time that widgets came on the WordPress scene, usually containing just the code to register the dynamic/widgetised sidebars, however they’re useful for so much more. If you don’t already have a functions file then just create a blank file in your theme directory called functions.php.

Think of the functions file as a way to add PHP to your site without needing to code up a plugin everytime you want to make a change. The functions file can contain your own functions to make jobs quicker on the frontend, or they can use the filter hooks available to plugin authors, to manipulate the way a lot of the template tags work.

The great point with this file as well is that you can copy it across to each new theme to save you time on having to make your usual custom changes. I tend to spend a good hour or two adding in my own additional bits of code into a new theme eg. the social bookmarks I prefer to use, my recent posts list with the comment count after the posts etc., however with the functions file I can create a function to do all of this and then just reference it in my theme with one line.

Simple Function

A simple function would be to display the social bookmarks I use/display at the end of my posts. I have the following function in my functions.php file:

< ?php
function display_sblinks($cssid = "social") {
	global $post;
?>
	<ul id="">
		<li>Bookmark this page at: </li>
		<li><a href="http://del.icio.us/post?url=http://www.bloggingtips.com/2009/01/04/using-a-functions-file/&amp;title=< ?php echo urlencode(the_title('','',FALSE)); ?>" title="Bookmark < ?php the_title() ?> on Del.icio.us">Del.icio.us</a></li>
		<li><a href="http://www.stumbleupon.com/submit?url=http://www.bloggingtips.com/2009/01/04/using-a-functions-file/&amp;title=< ?php echo urlencode(the_title('','',FALSE)); ?>" title="Submit < ?php the_title() ?> to StumbleUpon">StumbleUpon</a></li>
		<li><a href="http://www.spurl.net/spurl.php?url=http://www.bloggingtips.com/2009/01/04/using-a-functions-file/&amp;title=< ?php echo urlencode(the_title('','',FALSE)); ?>" title="Bookmark < ?php the_title() ?> on Spurl">Spurl</a></li>
    </ul>
< ?php } ?>

The code above accepts a value for the id of the list, or if one isn’t set then it uses the default of ’social’. Then it just outputs the list as normal, using the template tags for the URL and post title. Then all you would need is to place a call to the function when you want the list displaying ie.

<?php display_sblinks(); ?>

Or you can specify a different id name for the list eg.

<?php display_sblinks("sblist"); ?>

This is just a simple example of how you can use it.

Using a Filter

A more advanced function is to use one of the filter hooks to amend the default output. Last week I wrote about the wp_page_menu() function, and Dan Schulz made a comment with a good point, did we really need a div around the list, as a list is block level and could just have the specified class inserted into that.

So I had a play with a function and came up with the following code to go into your functions file (I don’t think it would warrant being a plugin to be honest). Feel free to use this of course :)

if (function_exists('wp_page_menu')) {
add_filter('wp_page_menu', 'pgmenu_filter');
function pgmenu_filter ($page_markup) {
preg_match('/^<div class=\"([a-z0-9-_]+)\">/i', $page_markup, $matches);
$divclass = $matches[1];
$toreplace = array('<div class="'.$divclass.'">', '</div>');
$new_markup = str_replace($toreplace, '', $page_markup);
$new_markup = preg_replace('/^<ul>/i', '<ul class="'.$divclass.'">', $new_markup);
return $new_markup;
}
}

The first line of this code checks that the function wp_page_menu exists to avoid any errors if you’re not using WordPress 2.7. Then we have a filter, which takes the output of the function wp_page_menu and runs it through the function pgmenu_filter, which does the following

  • Line 4 and 5 gets the value of the div class
  • Line 6 and 7 removes the surrounding div from the output
  • Line 8 replaces the ul tag with a ul tag and a class attribute, with the value of the original div class
  • Line 9 then returns the new output

Bearing in mind the output would be something such as

<div class="nav">
    <ul>
        <li class="current_page_item"><a href="http://www.bloggingtips.com/" title="Blogging Tips">Home</a></li>
        <li class="page_item page_item_3"><a href="http://www.bloggingtips.com/forums/">Forums</a></li>
        <li class="page_item page_item_8"><a href="http://www.bloggingtips.com/forums/local_links.php">Directory</a></li>
	<li class="page_item page_item_7"><a href="http://www.bloggingtips.com/themes/">Themes</a></li>
    </ul>
</div>

The new output would be

<ul class="nav">
        <li class="current_page_item"><a href="http://www.bloggingtips.com/" title="Blogging Tips">Home</a></li>
        <li class="page_item page_item_3"><a href="http://www.bloggingtips.com/forums/">Forums</a></li>
        <li class="page_item page_item_8"><a href="http://www.bloggingtips.com/forums/local_links.php">Directory</a></li>
	<li class="page_item page_item_7"><a href="http://www.bloggingtips.com/themes/">Themes</a></li>
</ul>

Conclusion

So as you can see, the functions.php file is actually a fairly powerful file to have in your theme directory. You can remove a lot of that custom coding from your theme files into their own functions, and then all of your custom code is in one place and easy to change.

Follow this blogger on Twitter!

Sarah Written by Sarah from Stuff By Sarah
Posted on January 4th, 2009 and filed under WordPress Coding & Design
Do not forget to subscribe to our RSS feed for updates
  • Digg This Post
  • Tweet This Post
  • Stumble This Post
  • Submit This Post To Delicious
  • Submit This Post To Reddit
  • Submit This Post To Mixx

14 Responses to “Using a Functions file”

Author comments are in a darker gray color for you to easily identify the posts author in the comments

  1. Blog Expert says:

    Really enjoyed the article. I love great tutorials like this.

  2. Dan Schulz says:

    Thanks for letting me know about the update via DM on Twitter, Sarah. (Of course, I prefer using an ID for the menu instead of a class, but that’s a dead easy change to make.)

  3. Sarah says:

    Hi Dan, no problem. Yes I’d use an id over a class, I think I was just sticking with class as the div was a class, but it’s easily changed as you say :)

  4. Steve says:

    Hi Sarah,

    Great article. I have a question for you:

    I want to use your social bookmarking code in a child theme for Sandbox. Because it’s a child I don’t want to touch the Index.php file to add , I just want to make an additionally functions.php file.

    Sandbox automatically assigns the class “post” to each post div. How can I automatically add your code after a div with the class “post”, by only adding code to the functions.php file?

    Any help you can provide would be appreciated.

    Thanks
    Steve

  5. Sarah says:

    Hi Steve, you would need to use a filter hook as explained in the second section. I would say to use the_content as the hook as you want to insert your code right after this, so you would get the output from the_content and then just add the social bookmarks output to the end of it and then return the final output ie. in a nutshell:

    add_filter ('the_content', 'add_socialbm');
    function add_socialbm ($output) {
    $socialbm_output = ""; // sort out your bookmark html
    $new_output = $output . $socialbm_output;
    return $new_output;
    }

    You’d then just need to modify the code to create your social bookmark html code.

    Hope that makes sense, if not then post up in the forum where it’s easier to write code!

  6. Steve says:

    Hi Sarah,

    Thank you for your quick response… your code worked perfectly!!

    However, I was wondering if this can be done on a div class? I only want to show information under the first post in index.php. Sandbox automatically assigns each post a numbered class; the first post is assign a “p1″ class.

    How can I show something only under the p1 class?

    Thank you so much!
    Steve

  7. Sarah says:

    Hi Steve,

    As far as I’m aware this can’t be done via a div class as you need to use rely on a WP tag to attach the content to. What you could do is create a global counter and then if the counter is equal to 0 you attach the bookmark output, then increment the counter, then on the second post the counter will be 1 and you can then ignore the bookmark data after that.

    However, bear in mind, using the_content will also add the bookmark data to the single post pages too, however that’s where you usually have it anyway.

    So in your functions file, outside of the function, create a counter and make it equal to zero, then set it as global. Then you can use this within the function.

    That’s just a guess, sorry, it’s a bit late here to start testing the code! Let me know if it works, if not I’ll work out a better solution tomorrow :)

  8. Steve says:

    Hi Sarah,

    The counter is a good idea. Thank you so much for your help!! Really great article.

    Thanks
    Steve

  9. Steve says:

    Hi Sarah,

    Sorry to bother you again. I went with your counter idea. The following code works it I place it in the INDEX.PHP file before ENDWHILE. But if I use it as a function it displays under every post. Why would it behave differently as a function?


    function under_first_post_ad() {

    if ($count == 0) : { ?>
    Adsense Code Goes Here
    <?php } endif; $count ; }

  10. Sarah says:

    Have you got the counter set outside the function? It needs to be along the lines of

    $count = 0;
    global $count;
    function under_first_post_ad() {
    if ($count == 0) :
    // adsense code here
    endif;
    $count++;
    }

    If that doesn’t work that way, move the global $count into the function before the if statement.

  11. Steve says:

    Sarah, You are a rock star!!

    This works great:


    function under_first_post_ad() {

    global $count;

    if ($count == 0) : { ?>
    Adsense Code Goes Here
    <?php } endif; $count++ ; }

  12. Steve says:

    (I can’t figure out how to make code appear in the comments)

  13. Sarah says:

    Glad to hear it worked :) As for code in comments, with the code tag you can’t insert blank lines, else WordPress automatically decides it’s a paragraph and it all falls apart!

Comments are closed.

Comments are closed since this post is older than 30 days. However, you can continue this discussion in our popular Blogging Forums

Subscribe To BloggingTips Via RSS Subscribe To Blogging Tips Via Email Follow Us On Twitter Find Out More About Our Newsletter
 

Blogging Tips Sponsors

Blogging Tips Newsletter

 

Blogging Tips Sponsors

 

Latest from the Blogosphere