How to echo field name as CSS class in Advanced Custom Fields (ACF) ?

Advanced Custom Field (ACF) is a free WordPress plugin to create custom field meta box in WordPress without having to code anything. If you have used ACF, you know how easy it is to use and create custom meta boxes in WordPress.

If you want to echo an ACF field value then you use use following code:

<?php the_field(‘field_name’); ?>

If you want to get the value of an ACF field as a variable then use following code:

<?php $variable = get_field(‘field_name’); ?>

But, what if you want to get the name of the field:

In that case, you have to use the ACF function called: get_sub_field_object

To echo a field name as class in the theme use following code:

<?php
$fieldname = get_sub_field_object('col_left'); 
$value = $fieldname['_name']; ?>

where ‘col_left’ is your field name.

This will output:

<div class="<?php echo $value; ?>">Blablabla</div>

Hope that works for you.

Leave a Reply