Taking Advantage of Functions.php in Wordpress Themes

— WordPress themes can optionally use a file where theme developers can add their own functions. This file acts like a plugin and gets automatically loaded during WordPress initialization, to get it working it just has to be named functions.php and reside in the theme folder.

Although not many themes seem to use it, it’s very powerful, you can use the functions inside for anything you choose. For me it helps me to define a library I can reuse to fasten up my work while keeping code clean and easy to manage. For example I have functions to list recent posts, easily display a copyright footer, highlight author comment, shorten text etc.

I have uploaded some of these functions I use as an example for you to download and try. To use them drop functions.php file in your theme folder.

→ Download the functions here

The Functions

Note: For the examples bellow i’m using function_exists() as a good practice, as if function doesn’t exist it wont break your theme.

wp_list_recent_posts( Amount, Categories, HTML before, HTML after );

Custom function to list recent posts.

  1. Amount: ( integer, default 5 ) – Number of posts to list.
  2. Categories: ( string, default all categories ) – Categories to include or exclude.
  3. HTML before: ( string, default <li> ) – HTML before the link.
  4. HTML after: ( string, default </li> ) – HTML after the link.

Function usage:

<ul>
// gets 10 recent posts from all categories except category 5.
       <?php if ( function_exists( 'wp_list_recent_posts' ) ) wp_list_recent_posts( 10, '-5' ); ?>
</ul>

shorten_text( Characters, Tail, Print );

Custom function to shorten the post content at a given number of characters.

  1. Characters: ( integer, default 250 ) – Number of characters to display.
  2. Tail: ( string, default “…” ) – Text to show after the shorten text.
  3. Print: ( boolean, default: true ) – Print the list or return it for PHP.

Function usage:

// wordpress loop
<?php   while (have_posts()) : the_post(); ?>
       <h1><?php the_title(); ?></h1>
       <div class="entry">

       // will shorten text after 150 characters
       <?php if ( function_exists( 'shorten_text' ) ) shorten_text( 150 ); ?>

       </div>
<?php  endwhile; ?>

highlight_comment( Class Name, Author ID );

Custom function to Highlight author’s comment.

  1. Class Name: ( string, default: autor-comment ) – Name of the CSS class desired.
  2. Author ID: ( integer, default 1 ) – ID number of the author user.

Function usage:

// Comments Loop
<?php foreach ($comments as $comment) : ?>
       <li id="comment-<?php comment_ID() ?>" class="<?php echo $oddcomment ?> <?php if ( function_exists( 'highlight_comment' ) ) highlight_comment(); ?>">
...
?>

display_copyright( Year, Separator, Tail );

Custom function to easily display a dynamic copyright information.

  1. Year: ( integer, default: current year ) – If given a previous year than the current one it will display it before the current one ( 2006 – 2008 ).
  2. Separator: ( string, default: ” – ” ) – Text used to separate the years ( in case a previous year has been declared ).
  3. Tail: ( string, default “. All rights reserved.” ) – Text to show after the copyright info.

Function usage:

<?php if ( function_exists( 'display_copyright' ) ) display_copyright(); ?>
// will display: <div id="copyright">&copy; 2008. Blog Name. All rights reserved.</div>

<?php if ( function_exists( 'display_copyright' ) ) display_copyright( 2006, ' to ', '. Some rights reserved.' ); ?>
// will display: <div id="copyright">&copy; 2006 to 2008. Blog Name. Some rights reserved.</div>

Conclusion

As you see the functions could be used for anything you want. I suggest you to give this a spin and try to incorpore it to your theme developing workflow, Cheers!

Tags: , , ,

Thursday, October 23rd, 2008 WordPress

→ If you find this post useful please consider inviting me a cup of tea :) Thanks!

43 Responses to “Taking Advantage of Functions.php in Wordpress Themes”

  1. This is so damn usefull. Do you have more examples? I’m a front-end designer that uses wordpress a lot. But I’m not developer. Would be very cool if you could show us some more :D

  2. Jonno Riekwel on October 24, 2008.
  3. Hi Jonno, im glad you found them useful. Will surely see to post more custom functions soon, thank you.

  4. Matt on October 25, 2008.
  5. Great tutorial! This will save me from adding function clutter to main theme files. As a warning, your shorten_text function might cause problems if the substr cuts off the content in the middle of a html tag. Maybe add a strip_tags to the post_content then apply_filters(‘the_excerpt’, $szText);

  6. Billy on November 4, 2008.
  7. Thanks for the suggestion Billy, zip file updated. Will post more functions as soon as i have some free time :) glad you found it useful.

  8. Matt on November 4, 2008.
  9. Hello!
    This is great, but you have a typo in usage of shorten text:
    if ( function_exists( ’shorten_text’; ) )
    Should be
    if ( function_exists( ’shorten_text’ ) ).

    Greetings!

  10. Ariel on November 19, 2008.
  11. Oops, thanks for the heads up Ariel ;)

  12. Matt on November 20, 2008.
  13. No problem, Im starting on wordpress, everything seems easiest, but I cant get on int completely. Anyway… I’d like to see more functions like this in the near future.

    Thank you back

  14. Ariel on November 20, 2008.
  15. Hello Matt,

    I just started to play around with WordPress (PHP, CSS, XHTML) and was wondering if I could drop code from plugins inside the functions.php so it would permanently be in the theme…Lets say like entering the ‘featured post’ plugin code so my theme would permanently have that in there?

    Or am I thinking about two different things?

    Also, any posts you talk about converting themes to magazine style or multiple colums or boxes of posts?

    Thanks for all the useful stuff I have already read about here that has given me ideas.

  16. tyronebcookin on November 22, 2008.
  17. @tyronebcookin Hi, thanks for stopping by. For your first question it will depend on the plugin you want to use, you can read an interesting post about it here. In regards converting themes to magazine like layouts my best advice would be to investigate/study the code from one of the many magazine type themes and then try to incorporate it with your own theme.

  18. Matt on November 22, 2008.
  19. Thanks Matt,

    It was an interesting post…I will have to think on that one. Maybe try it a couple of times, I have tested my first two attempts (at themes) in Xampp Lite on my computer so it will be fun to see how it works, or doesn’t before using them.

    I definitely have been doing your suggestion about looking into the code on magazine themes…it just gets a little hairy some days when i lOOk at it too long.

    Thanks!

  20. tyronebcookin on November 22, 2008.
  21. Oh! Matt, your code should help my new theme a lot easier. I want to try it today.
    nice work.

    Thanks.

  22. baby-bride on December 17, 2008.
  23. Matt,

    I’m look at using your code, but I’d like to know how I can modify it to do what I need.

    I’m using this line:
    if ( function_exists( ‘wp_list_recent_posts’ ) ) wp_list_recent_posts( 10, ‘105′ );

    But where I’ve got my category defined, I’d like that to change depending on the given category archive window I have open. So, there would be a list of recent posts in a given category and that list would change from page to page, category to category. What do I need in between my apostrophes? aka something along these lines: ‘the_ID’

  24. Tim on December 23, 2008.
  25. Hi Tim, thanks for the comment. To make that happen you need to send the category ID as parameter. Try something like this in your theme pages:

    < ?php
    if ( is_category() )
    {
    $this_category = get_category($cat);
    if ( function_exists( ‘wp_list_recent_posts’ ) ) wp_list_recent_posts( 10, $this_category->cat_ID );
    };
    ?>

  26. Matt on December 23, 2008.
  27. Matt;

    Thank you for all these functions. I’m interested in using the shorten_text function, but I must admit; I’m confused about the two versions you have illustrated. Mainly the version of the code contained in the zipped file and the one published on this page.

    I am totally new to wordpress so I hope you can understand my confusion.

    What I would like to do is not add any functions to the existing functions.php file; instead, I would like to “call” a “user-functions.php” file, which in turn contains the custom functions I like.

    I suspect I can do this by adding the following line to the existing functios.php file:

    “include_once (TEMPLATEPATH . ‘/user-functions.php’);”

    But what should my user-functions.php file contain? The “shorten_text” version you have published on this page or the version you have included in the down-loadable zipped file you have provided?

    Thanks in advance for clarifying this for me.

  28. Evan on December 29, 2008.
  29. Hi Evan, you are welcome. Im positive you can do that, you would have to include the code contained in the file for download.
    thanks for stopping by.

  30. Matt on December 29, 2008.
  31. Hi Matt;

    I’m impressed with your prompt reply.

    Ok, I follow you so far, now how about the “shorten_text” code you have published on this page. What do I do with it?

    Again, thanks in advance for your assistance.

  32. Evan on December 30, 2008.
  33. Hi Evan,

    Place the code contained in the zip file in user-functions.php. Include it in your for example single.php template and then in the same file look for the loop and insert the function there where you want to display the text:

    
    <?php   while (have_posts()) : the_post(); ?>
           <h1><?php the_title(); ?></h1>
           <div class="entry"> 
    
           <?php if ( function_exists( 'shorten_text' ) ) shorten_text( 150 ); ?> 
    
           </div>
    <?php  endwhile; ?>
    
  34. Matt on January 2, 2009.
  35. Hello I’ve used a custom fucntions.php file before but I have a question. Can the same be done for the classes.php file? I tried but it didn’t work. The reason is I made a menu nav bar with a sliding doors technique that requires an additional tag around the href link to implement the sliding doors button effect. I hack the classes.php that outputs the links and everything works fine but each time I upgrade WP I wind up having to redo this hack. I’m tired of repeating the hack over and over and would love to have a custom function that resides in the theme so the hack isn’t written over during upgrades.

    Any info appreciated
    Cheers

  36. edoriv on January 4, 2009.
  37. Hi Edoriv, You are correct, you should write your own function to generate the code you need for the navigation bar and either deploy it as a plugin or directly in your functions.php file. This way you dont have to change core files and you can easily move from one project to other. Im of course against hacking WordPress core files, and as far as I know you wont be able to do the same with classes.php.

  38. Matt on January 5, 2009.
  39. Dunno how code posting will work… converted but still dunno what to expect.

    Here’s what I use in my current theme.

    <h4 title="Previous Entries"><?php if(is_home()) echo "Previous"; else echo "Recent";?></h4>
    <?php if(is_home()) query_posts("cat=-3&showposts=5&offset=5"); else query_posts("cat=-3&showposts=5");?>
    <ul>
    <?php while (have_posts()) : the_post(); ?>
    <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
    <?php endwhile;?>
    </ul>

  40. Geoff on January 29, 2009.
  41. Changed it up with your little function (and modified the function).

    <?php $entry_list_type = "Recent"; if(is_home()) $entry_list_type = "Previous"; ?>
    <h4 title="<?php echo $entry_list_type; ?> Entries"><?php echo $entry_list_type; ?></h4>
    <ul>
    <?php if(is_home()) wp_list_recent_posts(5,’-3′,5); else wp_list_recent_posts(); ?>
    </ul>
    <span class="side-more-link"><a href="/archives/">more&hellip;</a></span>

    To add offsets:

    function wp_list_recent_posts( $iAmount = 5, $szCat = null, $szBefore = "<li>", $szAfter = "</li>" )
    {
    ( $szCat != null ) ? $szCat = "&cat=" . $szCat : $szCat ;
    $aRecentPosts = new WP_Query( "showposts=" . $iAmount . $szCat );
    while($aRecentPosts->have_posts()) : $aRecentPosts->the_post();
    $szReturn .= $szBefore . ‘<a href="’ . get_permalink() . ‘">’ . get_the_title() . ‘</a>’ . $szAfter;
    endwhile;
    echo $szReturn;
    }

  42. Geoff on January 29, 2009.
  43. Doh! I don’t really intend to spam your comments here so much. I just noticed that I posted your function, unmodified. Simple as my mod is, others might be interested and I messed it up… my apologies people. Here it is as I changed it.

    function wp_list_recent_posts( $iAmount = 5, $szCat = null, $szOff = null, $szBefore = "<li>", $szAfter = "</li>" )
    {
    ( $szCat != null ) ? $szCat = "&cat=" . $szCat : $szCat ;
    ( $szOff != null ) ? $szOff = "&offset=" . $szOff : $szOff;
    $aRecentPosts = new WP_Query( "showposts=" . $iAmount . $szCat . $szOff );
    while($aRecentPosts->have_posts()) : $aRecentPosts->the_post();
    $szReturn .= $szBefore . ‘<a href="’ . get_permalink() . ‘">’ . get_the_title() . ‘</a>’ . $szAfter;
    endwhile;
    echo $szReturn;
    }

  44. Geoff on January 29, 2009.
  45. Hi Geoff, thanks for sharing your modification! the offset parameter can certainly be very useful for certain situations.
    Cheers!

  46. Matt on January 30, 2009.
  47. very useful for certain situations. Again, thanks in advance for your assistance.

  48. ImprintVision on February 16, 2009.
  49. Hi, sorry for a basic question but I’m just starting out on this WP thing! The function for shortening the post content is so useful but I can’t figure out how to add a ‘more’ option to see the rest of the post.

    This is great stuff… thanks so much for inspiring.

  50. thurzo on May 25, 2009.
  51. Hi Thurzo, you could simple add below a handmade link to the post:

    <a href="<?php the_permalink() ?>" title="read more">read more</a>

    Hope that helps, Cheers!

  52. Matt on May 27, 2009.
  53. I was wondering, designing some themes myself and never trie adding an admin panel for my theme. I know this is done inside functions.php but no idea how to add it there. All I can find is stuff on plugins…any help would be greatly appreciated.

    Kind Regards,
    WebHead

  54. WebHead on December 7, 2009.
  55. Hey very useful information to me………..
    Thanks to the admin…….. cheers ;)

  56. str on December 18, 2009.
  57. Hi Great post thanks for sharing.

  58. Scott @sydneydesign on January 23, 2010.

About Me

Matt Varone - Matias Varone - sksmatt
HI there,

I'm a freelance creative web developer, UI designer and hobbyist musician.

Twitter Status

Flickr Gallery

    Clutter drawerCS4 Replacement iconsCS4 Replacement iconsMagic

Scrnshots Gallery

  • Screenshot from ScrnShots.com
  • Screenshot from ScrnShots.com
  • new site im working on
  • Screenshot from ScrnShots.com