davidgagne.net

  • About
  • Archives
  • Twitter
  • Facebook
  • bartender.live
  • GitHub
  • LinkedIn

WordPress Wednesday: Safe Function Calls

July 8th, 2009 @ 5:45 am PDT
WordPress Wednesday: Safe Function Calls

If you’re editing a WordPress theme template file by adding a call to a plugin’s function, you need to be careful. In six months or a year you’re going to deactivate or delete that plugin, and you’re going to get a big ugly fatal PHP error on your blog. You can avoid it, though, by adding a single if statement.

WordPressLet’s say you’ve installed the plugin “Big Bob’s TightyWhitey Plugin” (bobstightywhitey.php). This magical pretend plugin prints the date of the last time you changed your underwear. To call it, you just add this line to your single.php template:

TightyWhitey();

The problem is that when you deactivate or delete “Big Bob’s TightyWhitey Plugin”, WordPress is no longer going to load bobstightywhitey.php, so it will have no way to execute the TightyWhitey() function. And that, my friend, will cause your blog to crash and burn.

This awesome function is called function_exists.

Luckily for all of us, we don’t have to worry about it. There’s a handy little function you can call — before you call a function — that checks to see if the function you’re calling exists. (That’s not as confusing as it might sound. Go ahead. Read it again, slowly this time.)

You’re never going to believe this … this awesome function is called function_exists.

So instead of calling just TightyWhitey(), you check if TightyWhitey() is there first:

if ( function_exists( 'TightyWhitey' ) ) TightyWhitey(); 

That’s all you have to do. If you forget that you’ve added this function to one of your site’s templates and delete the plugin, everything will be fine. (Your site might look a little strage, though. If you’ve got a page with a big 22px header that is supposed to display the date you last changed your underwear, it simply won’t show anything. And, sadly, if you were using the output of TightyWhitey() as an input parameter for some other function, and that function doesn’t have proper error-handling, you might still be screwed. I can only help you so much.)

More posts tagged:
code / PHP / plugins / wordpress / wordpresswednesday

More posts categorized:
Programming Web Design

More posts from:
July 2009 / 2009

Post navigation

Previous Post
Previous Post iTunes Tuesday: Show in Playlist
Next Post
Next Post #FridayFive: My Favorite Nuts

Search


If credit card debt or student loan payments are killing you, I highly recommend taking a look at SoFi. Their low rates and incredibly quick and simple application process might be just what you need.

  • Take Control of Your Debt

© David Vincent Gagne. All rights reserved. Custom WordPress Theme by Jacket Industries.