Shorter location rules in ACF
Have you ever used registerfieldgroup() for a packaged theme or plugin? Most people haven't. In fact, http://advancedcustomfields.com doesn't even have documentation on the function. Where this function comes into play is if you try to register a field group (and subsequently, fields) with PHP using the ACF API. The easiest way to see this is by using ACF's built in PHP export. The subsequent block of code that is rendered can be pretty daunting, and in my opinion, a little bloated depending on your application. For people exporting fields for a theme, it's probably fine, but for someone writing a plugin that dynamically creates fields, this behemoth can be a pain to write and manage. My biggest beef is with the "location" key passed to registerfieldgroup().
"Location" accepts a multidimensional array, mapping each key => value to the boolean-esque rules that are used to assign fields to a particular location in your WP installation. For example, only show this field for this particular page and the user is an administrator. Where this get's to be a little overwhelming, is when you are registering a field to a lot of different areas, yet ignoring a lot of others. One example I've used recently is widgets. I want to add a text field to all the default WP widgets but not all the other ones. My location value may look something like this:
[gist https://gist.github.com/6edebde58013f429b0bf /]
You can see how that can start to get a little ridiculous right? 60 lines for one value? Especially when most of it is repeated! So I wrote a function for generating these giant location arrays when all the values are similar.
[gist https://gist.github.com/ac2f976d8929c7bd18c2 /]
In a nutshell you pass an array of locations that all share a similar a similar parent. In the case above, they were all widgets. Then you supply the operator to compare against and an $extended boolean parameter. The $extended variable is for when each location is a new rule. For example, I want to show this field when the widget is "Archives" or when the widget is "Meta." The default logic to show a field is that all the parameters must match (and operator). We then pass this function to a variable which we use with the location rule of registerfieldgroup().
$locations = acfw_location_rules( $wp_widgets, 'widget', '==', true );
register_field_group( array (
'location' => $locations,
// rest of the function goes here ...
) );
Hopefully you find uses for this in your own projects. I know for me, it was definitely a lifesaver for generating long arrays for location rules. I will admit, not being able to set to parameter for something like both "Widgets" and "Administrators" is a limitation, but I'm working on an elegant solution for those instances.
Leave a comment below if you have any questions! I'd be happy to help! Check out http://reddit.com/r/advancedcustomfields if you want to be part of a community all about ACF.