Safely using Advanced Custom Fields via Wrapper Functions

Those who know me or have seen me speak at WordCamps know that Advanced Custom Fields is my all-time favorite WordPress plugin. The speed with which you can build robust custom options panels via this plugin is absolutely unrivaled, and as a result it’s become one of my primary tools for building highly customized & user-friendly interfaces within WordPress. I’ve used the plugin on countless projects and have had amazing success with it. Despite the plugin’s many advantages, however, there is a substantial risk associated with using it if you do not have exclusive control over the management of a website’s plugins.
The Problem
A lot of sites I’ve developed have front-end components that rely heavily on data stored by Advanced Custom Fields. I do this to make customizing the website as easy as possible for end-users, but this comes with a rather large risk: If Advanced Custom Fields ever becomes deactivated or removed by accident, the website could start functioning improperly or (at worst) cease to work altogether. This is because WordPress can only understand how to use ACF’s functions if the plugin is enabled. Without ACF enabled, functions such as the_field() and get_field() have no meaning and will either cause the site to throw a Fatal Error, or display incomplete pages.
I realized that this was an unacceptable risk to be taking with my clients’ websites, but I still very much wanted the convenience of using this amazing plugin. Fortunately, the solution turns out to be rather simple: All we need to do is use “wrapper functions” to provide fallbacks for our data in the event that ACF is not active.
The Code
Huge kudos to Steve Grunwell for publishing the first draft of these functions. After finding his post, I made some further changes to the functions to make them mirror those of ACF more closely. To use them, simply add the functions to your WordPress functions.php file and use them throughout your templates in place of the regular ACF functions.
TIP: When calling these functions in your code, always try to specify a default value for each field using the functions’ $default parameter. When the function runs, it will first check if the corresponding ACF function exists, and whether a value exists for the specified key. If neither is true, the wrapper function will return (or echo) your default value instead. In doing so, you can rest assured that if Advanced Custom Fields is ever deactivated your website will still remain functional.
Comments