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:

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

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 ); ?>
<?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">&amp;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">&amp;copy; 2006 to 2008. Blog Name. Some rights reserved.</div>


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!

Reactions (49)

  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. Pingback Useful Links (24/10/2008) | Apramana

  3. Hi Jonno, im glad you found them useful. Will surely see to post more custom functions soon, thank you.

  4. Pingback Taking Advantage of Functions.php in Wordpress Themes | bloground.ro - Blogging resources, WordPress themes and plugins for your development

  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. 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.

  7. Pingback Geek Links on jQuery, PHP, CSS, XHTML, Web Design, Fireworks, Flash | JasonCypret.com

  8. Pingback Wordpress functions.php - Code Candies

  9. Pingback bluelectric.org » Linksammler

  10. Pingback WordPress-Functions für Themes basteln und derlei Dinge | Phase 5

  11. 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’ ) ).


  12. 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

  13. tyronebcookin

    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.

  14. @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.

  15. tyronebcookin

    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.


  16. Pingback Sacando provecho del archivo “functions.php” en los temas de Wordpress

  17. Pingback Fondos de Pantalla » Blog Archive » Sacando provecho del archivo “functions.php” en los temas de Wordpress

  18. Pingback WordPress functions to supercharge your Theme! - Yoast - Tweaking Websites

  19. baby-bride

    Oh! Matt, your code should help my new theme a lot easier. I want to try it today.
    nice work.


  20. 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’

    • 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 );

  21. 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.

    • 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.

  22. 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.

    • 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 ); ?>
      <?php  endwhile; ?>
  23. 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

    • 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.

  24. Pingback Funciones para tus temas en WordPress at Bit’n'Byte

  25. 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");?>
    <?php while (have_posts()) : the_post(); ?>
    <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
    <?php endwhile;?>

  26. 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>
    <?php if(is_home()) wp_list_recent_posts(5,’-3′,5); else wp_list_recent_posts(); ?>
    <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;
    echo $szReturn;

  27. 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;
    echo $szReturn;

    • Hi Geoff, thanks for sharing your modification! the offset parameter can certainly be very useful for certain situations.

  28. Pingback Agrega funcionalidad a tu Wordpress : Salva G. Mendez

  29. thurzo

    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.

    • 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!

  30. Pingback Testing2 » X-Press-See

  31. Pingback Project 3 « Crìmic Design Studio

  32. 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,

  33. Hey very useful information to me………..
    Thanks to the admin…….. cheers ;)

  34. Pingback Series Posting in Wordpress

  35. Linda Carter

    I’m still missing how I’m supposed to call these from a template file. What’s the syntax to call, say, the copyright function?


  36. kamaludeen

    very useful for certain situations. Again, thanks in advance for your assistance.

  37. Thanks , It was just the help i needed , thanks again.

  38. Hello dear

    My question if is there any way i can call physical php file present in wordpress theme folder by writing the file name or something in url i dont want to use wordpress admin, however i am ready to write any kind of php code in functions.php file.

    My question is similar to this thread http://wordpress.org/support/topic/custom-files-with-permalinks-from-theme-folder Please reply as i am subscribed to this post’s comments thread.

  39. Gareth

    Hi Matt – Great post, however I have a question.
    I’ve edited my themes functions.php file and accidently replaced it with the functions.php file that sits in the wp-includes folder. I’m now getting a server error and cannot access my site or my login for the site – http://www.onefamilyfellowship.co.zw/ Is there a default functions.php file that I could download? Thanks – Gareth