Add profile fields using Advanced Custom Fields

I was working on a WordPress site for a client this week and wanted to add a new field to the user profile, but not one that the user could themselves edit.  And I thought that this was going to be really complicated.

Advanced Custom Fields Pro to the rescue!

If I’ve not talked about this plugin before, then I should have.  It’s so powerful by itself, and there’s loads of third party extensions too, adding the ability to create custom fields for any post/page/etc. in WordPress.

Not only can you do this within the admin panel, but you can export the configuration into PHP code and then paste it directly into your theme or plugin, so that the user doesn’t need to have the plugin themselves – that’s super slick!

But this week I learned that you can also target the user profile, using the Location rules…

I’m selecting “User Form” as the location and saying that it should be equal to “All” (you can Add, Add/Edit or Register if you prefer).  In this example I am also setting this to only show if the “Current User” is not equal to “Exhibitor”, as this is the user role that the field applies to, and I don’t want them to be able to see/edit this field themselves.

You can then reference the user field like this…

$current_user = wp_get_current_user();
$custom_field = get_field('custom_field', 'user_' . $current_user->ID);

So what I thought was going to be a complex job turned out to be only about 15 minutes tops – I love it when that happens.