How to check for field groups in WordPress Advanced Custom Fields plugin?

I’m using the acf Advanced Custom Fields plugin for WordPress.
I’m working with a generic template that outputs all field groups by default.
As some fields are only shown on specific pages I’d like to determine what fields need to be outputted.
My current workaround is the following:

1, I created a acf- field group (e.g. with the name “My Field Group”) in
the backend;
2, I set a role in the acf-menu for “My Field Group” to
show it only on e.g. a specific page (the role could also be a category etc.)
3, I created a custom field with a checkbox and the
name “mygroup” within “My Field Group” that always returns “yes”.

Read More

4, Then in the code I can check if the group “My Field Group” is available on a
page by checking the value of the custom field “mygroup”. If yes, it will return all fields of “My Field Group”

The code:

//check if the field group "My Field Group" is available by checking the value of its custom field "mygroup" 
<?php if(get_field('mygroup') == "yes") { ?>
    <div>
        //load all other fields in the field group "My Field Group"
    </div>
<?php } ?>

As this requires an additional field only to check if the field group is available on a page (respectively to determine the role), I was wondering if there is a more elegant way to achieve that

acf editor

page

Update:
Here’s the feedback from the programmer:

ACF does not save any information about the specific field group that
appeared on the post, only the field values.

I believe that your method is minimal, efficient and smart. I would
continue to use this.

Cheers Elliot

Related posts

Leave a Reply

1 comment

  1. For simply checking if the field mygroup is enabled, use:

    // call the function only once
    $group = get_field('mygroup');
    
    if( $group ) { 
        ?>
        <div>
            <?php do_your_magic_with_the_other_fields(); ?>
        </div>
        <?php
    } 
    

    For checking for the whole My Field Group:

    An ACF Field Group is a custom post type stored in wp_posts table. The fields inside this Field Group are stored in wp_postmeta table.

    So, you’ll have to check for the post existence.

    acf field group

    Same “field group” in the database:

    acf field group in the database
    click to enlarge ⤴


    Solution: use get_page_by_title()

    In my example:

    if( get_page_by_title( 'TimMaia', OBJECT, 'acf' ) )
    {
        // Your stuff
    }