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

Post the first comment:

I'll never share your email address and it won't be published.

What Is This?

davidgagne.net is the personal weblog of me, David Vincent Gagne. I've been publishing here since 1999, which makes this one of the oldest continuously-updated websites on the Internet.

bartender.live

A few years ago I was trying to determine what cocktails I could make with the alcohol I had at home. I searched the App Store but couldn't find an app that would let me do that, so I built one.

Hemingway

You can read dozens of essays and articles and find hundreds of links to other sites with stories and information about Ernest Hemingway in The Hemingway Collection.