Black Friday 50% OFF! Coupon “BLACKFRIDAY50” Ends in:

0

Days

:

0

Hrs

:

0

Mins

:

0

Secs

Shop now!
WPLake > Learning Hub > ACF Group Field: Complete Guide with Code Snippets

ACF Group Field: Complete Guide with Code Snippets

Discover how to use the ACF Group field to organize, display, and manage multiple field types efficiently with practical tips and alternatives.

Key Points at a Glance

  1. ACF Group Field Overview: The ACF Group field in the Pro version allows organizing multiple fields into a single set, simplifying complex data structures.
  2. Field Types: Within a Group field, you can add any field type, from basic text fields to advanced fields like Relationship and Gallery.
  3. Nesting and Layouts: Groups can be nested within other groups and can be displayed using Block, Row, or Table layout options.
  4. Storage Format: Subfields within a Group field are stored with a prefix derived from the Group field name, e.g., group_first_name.
  5. Alternative Fields: For repeatable or complex field structures, consider the ACF Repeater field or ACF Flexible Content field as alternatives to the Group field.
  6. Loading and Displaying Sub-Fields: To display Group fields, utilize the Advanced Views Framework for streamlined template creation, or use custom code with the get_field() function.

Table of Contents

The ACF Group field is a powerful and flexible feature of the Advanced Custom Fields plugin, available exclusively in the Pro version. Categorized under the Layout group, this advanced field type allows you to organize multiple fields into a single set, making it easier to manage complex data structures.

For content editors, the fields within the group appear as one cohesive section, creating a more streamlined experience. For developers, all the fields in the group are stored as a single array, preventing naming conflicts with other fields and making the data retrieval process simpler.

Within a group field, you can add any type of field, from basic ones like text fields to more advanced types such as the Relationship or Gallery fields. Plus, ACF offers flexibility - if needed, you can nest a group field within another group, allowing for more complex structures without limitation.

Note: The ACF Group field is purely organizational and does not support repeating fieldsets. If you need repeatable fields, the ACF Repeater field is a better option. However, you can still include a repeater field inside a group for more advanced use cases.

ACF Group field UI

ACF Group field
The ACF Group field is a container for other fields within a local scope.

The layout setting allows you to customize the appearance of fields within the group. There are three options available: Block, Row, and Table.

Block layout of the ACF Group Field
The "Block" option in the layout settings stacks all inner items, including the labels, into a column.
Row layout of the ACF Group field
The "Row" option in the layout settings arranges every field into a horizontal row.
Table layout of the ACF Group field
The "Table" option in the layout settings enables a table appearance, with field labels serving as column names.

ACF Group field-related addons

ACF addons can be an important part of the workflow, and there are several addons especially useful for the ACF Group field:

  • ACF to Custom Database Tables is an add-on for Advanced Custom Fields that saves your custom field data in a dedicated, structured database table, improving organization and performance.
  • ACF Quick Edit Fields enhances the WordPress admin experience by adding Quick Edit functionality to Advanced Custom Fields. This plugin allows you to quickly view and edit ACF field values directly from the list views.
  • ACF Tooltip enhances the user experience by managing lengthy instruction texts in ACF fields. Instead of cluttering the edit screen, this plugin allows you to add tooltips to field labels, keeping the interface clean and space-efficient.
  • WPGraphQL for ACF allows you to expose ACF fields and field groups to GraphQL, enabling seamless querying of ACF data within your GraphQL queries.

Group fields in other meta-field plugins

If you're exploring alternatives to ACF, you'll find similar functionality in other meta-field plugins. For instance, the Meta Box plugin offers a Group feature that provides comparable capabilities for organizing fields into sets.

To dive deeper into how these plugins compare, take a look at our detailed meta-field plugin comparison for a full breakdown of the strengths and differences between ACF and its competitors.

1. ACF Group field essentials

1.1) Field settings

In addition to the common settings like name and label, the ACF Group field includes some field-specific options:

  1. Sub Fields:
    This setting allows you to define the individual fields that will be part of the group. You can add any field type within the group, from simple text fields to more advanced fields like Gallery.
  2. Layout:
    This setting determines how the fields within the group are visually arranged:
    Block: Displays fields stacked vertically, similar to a standard form layout.
    Table: Arrange the fields in a table-like structure, with rows and columns.
    Row: Places fields in a horizontal row, creating a compact layout for displaying multiple fields side-by-side.

1.2) Storage format

The ACF Group field influences the naming convention for its subfields by prefixing each subfield with the name of the group field. This helps maintain clarity and avoid conflicts with other fields.

ACF Group sub fields in DB
All subfields inside the group are saved into the database with the group prefix.

When storing data, the format for each subfield is {group-field}_{sub-field}. For example, if you have a Group field named group and it contains text fields named first_name and last_name, the stored field names will be group_first_name and group_last_name.

The saved value retains the original value of each subfield and depends on the field type and settings.

1.3) Supported field locations

The ACF Group Field can be utilized across various locations, and its data is consistently managed regardless of where it is applied:

  1. Post Objects (Post, Page, Media Attachment, CPT Item, WooCommerce Product):
    The Group field data for all content types - including posts, pages, media attachments, and custom post types - is stored in the wp_postmeta table. It is associated with the relevant post or custom post type item, ensuring that the grouped data is linked to the correct content.
  2. Options Page:
    When used on an ACF Options Page, the Group field's data is stored in the wp_options table. This setup makes the grouped data available as a global site-wide setting, ideal for options like global banners or site settings.
  3. User Profiles:
    Adding the Group field to user profiles stores the data in the wp_usermeta table, linked to the specific user. This is useful for storing additional user information or settings that are unique to each user.
  4. Terms (e.g., Post Categories):
    The Group field can be attached to terms, such as post categories, tags, or custom taxonomies. In this case, the data is stored in the wp_termmeta table, connected to the specific term, making it available for term-specific data.
  5. ACF Gutenberg Block:
    When used within custom ACF Gutenberg blocks, the Group field's data is stored in the post_content field as part of the block's JSON data structure in the wp_posts table. This integrates the grouped data directly with the block’s content.

1.4) Alternative field types

As noted earlier, the ACF Group field is designed primarily for organizational purposes and does not support repeating fieldsets. If you require repeatable fields, the ACF Repeater field is a more suitable option.

For more flexible structures, consider the ACF Flexible Content field. This field allows editors to arrange various field sets in a custom order, providing greater versatility for complex content layouts.

2. Use cases of the ACF Group field

The ACF Group field is a powerful tool for improving the user interface and managing data efficiently, particularly when working with complex or large sets of fields.

Here are some real-life examples of how the ACF Group field can be used:

  1. Team member profiles:
    On a company website, you might use a Group field to manage team member profiles. The group could include fields for name, position, bio, and social media links. By grouping these fields, you keep all relevant information together and ensure that each profile is organized in a consistent way.
  2. Product specifications:
    For an e-commerce site, the Group field can be used to handle product specifications. For instance, a Group might include fields for dimensions, weight, and color options.
  3. Event details:
    If you're managing event information, you could use the Group field to bundle fields such as event date, time, location, and description.
  4. Client testimonials:
    On a testimonial page, you might use a Group field to manage client feedback. The group could include fields for client name, testimonial text, and client photo.

3. ACF Group field support in Themes and Builders

ACF is one of the most popular WordPress plugins, and it's supported by many page builders right out of the box. However, most of these integrations are basic, providing limited control over the layout or lacking support for advanced field types like Group.

To achieve universal compatibility with any theme and page builder while gaining advanced control over your layout, consider using the Advanced Views Framework or custom code snippets as discussed in the following chapter.

Here's a snapshot of the built-in features offered by some of the most popular WordPress themes and page builders for displaying ACF Group fields:

Theme/BuilderACF-related featureACF Group type support
Astra-no
AvadaDynamic Contentno (not declared)
BeaverACF Moduleyes
BricksDynamic datano (not declared)
DiviACF Moduleno (not declared)
ElementorDynamic Tagsno (not declared)
GeneratePress-no
Gutenberg-no
KadenceDynamic Contentno (not declared)
OceanWP-no
Visual ComposerDynamic Contentno (not declared)
WPBackery-no

While this list may seem brief, many themes come with their own page builders. Check your theme’s documentation for guidance on displaying ACF Group fields, or refer to the universal methods outlined below for a more flexible approach.

4. Code snippets for the ACF Group field

ACF functions and their responses are essentially wrappers around built-in WordPress features. This means that to load and display field values, you need to be familiar not only with ACF but also with core WordPress classes and functions. Additionally, writing markup from scratch and manually escaping data can be time-consuming.

To streamline development, you can use the Advanced Views Framework. This WordPress framework offers smart templates for the front end, simplifying post queries and template creation. It generates default markup and automatically loads the escaped data into the template, allowing you to focus on the layout itself.

Unlike drag-and-drop page builders, smart templates in Advanced Views are modular and based on a template engine (Twig or Blade), providing full control over the markup and helping you avoid the pitfalls of global CSS and JavaScript files. The framework natively supports all ACF field types, along with other data sources.

Note: AVF: Lite edition is free and supports all plain ACF field types, but Group is a multi-level field, supported only in the AVF: Pro edition. The good news that Pro contains a lot of useful features, including an option for custom Gutenberg blocks, which allows to turn any element into the Gutenberg block without any React coding.

Below are examples for both Advanced Views Pro and custom code:

4.1) Loading and displaying sub-fields

Using Advanced Views Pro

To display the Group fields, follow these steps as outlined in the AVF Group documentation:

  1. Create a new View:
    Start by creating a new View in the AVF.
  2. Select the Group Field:
    From the field list, choose the Group field you want to display.
  3. Assign Sub Fields:
    Switch to the Sub Fields tab and select the specific subfields within the Group field.
  4. Publish the View:
    Click the Publish button to save your configuration.
  5. Use the Shortcode:
    Copy the generated shortcode and paste it into a post, or page, or create a custom Gutenberg block.

That’s it! Advanced Views will automatically generate the template based on the selected subfield types and display the data accordingly. To customize the appearance of your output, you can add CSS rules in the CSS code field of your View. These styles will be applied by AVF automatically to the pages where the View is used.

Loading from different locations: To load a field from different locations (e.g., user profile), use the object-id shortcode argument.

AVF supports multiple nested levels, allowing for complex field structures. For more information on working with nested groups, refer to the AVF Nested group Docs.

Using custom code

To retrieve data from the ACF Group field, use the ACF get_field() function. You need to specify the source from which to load the value as the second argument. The function will return an array containing all the sub-field values.

The exact content of the array depends on the field types and their settings. Don't forget about security, and escape the output as shown below.

Example code for a Group field with the name team_member, which includes an ACF Image field (profile_image) and an ACF Relationship field (projects):

// Get the Group field data
$team_member = get_field( 'team_member' ) ?? array(); // from the current post
$team_member = get_field( 'team_member' , 10) ?? array(); // from a specific post by ID
$team_member = get_field( 'team_member', 'option' ) ?? array(); // from the options page
$team_member = get_field( 'team_member', 'user_1' ) ?? array(); // from the user by ID
$team_member = get_field( 'team_member', 'category_2' ) ?? array(); // from the category term with ID 2
$team_member = get_field( 'team_member', 'genre_3' ) ?? array(); // from the custom genre term with ID 3

// Check if the Group field has data
if ( $team_member ) {
	echo '<div class="team-member">';
	// Retrieve and display the Image field using WP function
	$profile_image = $team_member['profile_image'];

	if ( $profile_image ) {
		echo wp_get_attachment_image( $profile_image['ID'], 'full', false, array(
			'alt'   => esc_attr( $profile_image['alt'] ),
			'class' => 'team-member__image',
		) );
	}

	// Retrieve and display the Relationship field as links
	$projects = $team_member['projects'];

	if ( $projects ) {
		echo '<ul class="team-member__projects">';

		foreach ( $projects as $project ) {
			$project_title = get_the_title( $project->ID );
			$project_url   = get_permalink( $project->ID );

			printf(
				'<li><a class="team-member__project" href="%s">%s</a></li>',
				esc_url( $project_url ),
				esc_html( $project_title )
			);
		}

		echo '</ul>'; // close .team-member__projects
	}
	echo '</div>'; // close .team-member
}

Once you’ve added the code to your target template and incorporated the necessary markup for the fields, you can move on to styling. You'll need to add CSS rules to define the appearance of these fields.

There are two main approaches for this: You can either add the styles to a global style.css file, which will affect the entire site, or you can use template-specific assets. The latter approach, adding styles to a template-specific stylesheet is generally preferred. This method allows you to apply styles precisely where needed without affecting other parts of your site.

4.2) Updating the Group field programmatically

To update the Group field programmatically, you can use the ACF update_field function. Since this field stores sub-fields in an array, the data you pass must be an array of sub-field values.

add_action('acf/init', function() {
    // Define the group field data
    $group_data = array(
        'sub_field_1' => 'Value 1', // Replace with your actual sub-field key and value
        'sub_field_2' => 'Value 2', // Replace with your actual sub-field key and value
        // Add more sub-fields as needed
    );

    // Update the Group field
    update_field('my_group_field', $group_data, 1); // Replace 'my_group_field' with your Group field key, and 1 with the target post ID
});

If you need to update the Group field on a user or term object, you must add the appropriate prefix, just as shown in the "loading" field value section.

Note: You should call the update_field function inside the acf/init action, or in any hooks that happen later.

5. Querying by the ACF Group Field

Querying data from sub-fields within an ACF Group field is similar to querying plain fields, such as an Image field. The main difference lies in how you reference the fields.

  • Field name prefix:
    When querying sub-fields within a Group field, use the group prefix to access the individual sub-fields. For example, if your Group field is named team_member and includes sub-fields name and role, you should query them as team_member_name and team_member_role.
  • Storage Locations:
    The way you query the Group field data may vary depending on where the data is stored.

Below are examples of how to query a Text field with the title name within a Group field, with the team name, based on different storage locations:

5.1) By postmeta (Post, Page, Any CPT)

Using Advanced Views Framework:

If you're using the AVF: Pro edition, querying by ACF Group sub-fields is straightforward with Meta Queries. You need to create a Card, choose the target Group sub-field in the Meta Fields tab, and define the desired value. It can be a static id or pointer to another field. Then the framework will take care of the rest.

Using WP_Query

For custom queries, you can use the built-in WP_Query class:

$args = array(
    'post_type' => 'post', // or your CPT
    'post_status' => 'publish',
    'posts_per_page' => -1, // means unlimited
    'meta_query' => array(
        array(
            'key'   => 'team_title', // target field name
            'value' => 'value', //  target value
        )
    )
);
$query = new WP_Query($args);
foreach($query->get_posts() as $post){
 // todo WP_Post $post
}

5.2) By termmeta (Terms)

Here we need to employ the WP_Term_Query class:

$args = array(
    'taxonomy'   => 'category', // Replace with your taxonomy
    'meta_query' => array(
        array(
            'key'     => 'team_title', // target field name
            'value'   => 'value', // target value
        )
    )
);

$term_query = new WP_Term_Query($args);

foreach ($term_query->get_terms() as $term) {
    // Process each WP_Term object
    // Example: echo $term->name;
}

5.3) By usermeta (user profile)

In this case, we need to use the WP_User_Query class:

$args = array(
    'meta_key'     => 'team_title', // target field name
    'meta_value'   => 'value', // target value
);
$user_query = new WP_User_Query($args);

foreach ($user_query->get_results() as $user) {
    // Process each WP_User object
    // Example: echo $user->user_login;
}

5.4) Inside ACF Blocks

ACF Blocks save their data as JSON in the post_content. This data cannot be queried directly. However, if you enable the "Save in Meta" feature for ACF Blocks, the field values are also saved in post meta, allowing you to query them similarly to other postmeta fields.

6. Related Group field filters and hooks

ACF offers a variety of filters and hooks that enable you to modify field data and behavior, extending WordPress's core hooks functionality. You can utilize the standard add_action and add_filter functions to attach custom code to these hooks.

Below are some of the most commonly used hooks along with the ACF Group field type:

6.1) acf/load_field

The acf/load_field filter allows you to modify the field settings before it is displayed on the editor's screen. This filter is particularly useful for dynamically adjusting the field's configuration, such as setting default values, changing labels, or customizing available options.

add_filter('acf/load_field/name=my_group_field', function (array $field): array {
    // Modify the field settings as needed
    $field['instructions'] = 'Please fill out all group sub-fields.';

    return $field;
});

6.2) acf/render_field

The acf/render_field action allows you to add custom HTML before or after a field's input on the editor's screen in the WordPress admin. This can be particularly useful for adding custom-styled text, icons, styles, or additional interactive elements to enhance the field's functionality.

add_action('acf/render_field/key=field_123456789abc', function (array $field): void {
    // Your custom HTML
    echo '<div class="my-custom-class">Custom field-related element</div>';
}, 10, 1);

Note: By default, the acf/render_field action is triggered after the field input has been printed. If you need to print your HTML before the input, you should set the priority number to 9 or lower in the third argument of the add_action WordPress function.

6.3) acf/validate_value

Use the acf/validate_value filter to validate the values entered into the field. You can ensure that the entered value meets specific criteria:

add_filter('acf/validate_value/name=my_group_field', function($valid, $value, array $field) {
    if (true !== $valid) {
        return $valid; // Skip validation if there is an existing error
    }

    // Custom validation: Ensure at least one sub-field is filled out
    if (empty($value['sub_field_1']) && empty($value['sub_field_2'])) {
        $valid = 'Please fill out at least one sub-field in the group.';
    }

    return $valid;
}, 10, 3);

6.4) acf/validate_save_post

The acf/validate_save_post action allows you to perform custom form validations before saving ACF fields. This is particularly useful when you need to validate one field's value based on another field's input or enforce specific rules across multiple fields.

add_action('acf/validate_save_post', function () {
    // Retrieve the Group field values from ACF fields
    $group_field_1 = $_POST['acf']['field_group_id_1'] ?? [];
    $group_field_2 = $_POST['acf']['field_group_id_2'] ?? [];

    // Check if at least one Group field has values
    if (empty($group_field_1) && empty($group_field_2)) {
        // Add validation errors if neither Group field has values
        acf_add_validation_error('field_group_id_1', 'At least one of the Group fields must contain values.');
        acf_add_validation_error('field_group_id_2', 'At least one of the Group fields must contain values.');
    }
});

Tip: To find the field key, navigate to the ACF field group in the WordPress admin. Click on the Screen Options button at the top right corner of the page, then check the Field Keys option. Once enabled, the field keys will be displayed next to each field name in the group.

6.5) acf/save_post

The acf/save_post action is triggered when the current item (page/product/user) is saved. You can use it to perform any additional actions, e.g. updating related data.

add_action('acf/save_post', function ($post_id) {
    // Retrieve the Group field value
    $group_data = get_field('my_group_field', $post_id); // Replace with your Group field key

    if (!$group_data) {
        return;
    }

    // Process sub-fields within the Group field
    $related_post_id = $group_data['sub_field_1']; // Example sub-field

    if ($related_post_id) {
        // Fetch and update related items
        $related_items = get_field('related_item', $related_post_id) ?: [];

        if (!in_array($post_id, $related_items, true)) {
            $related_items[] = $post_id;
            update_field('related_item', $related_items, $related_post_id);
        }
    }
});

Stuck with development or facing an issue?

WPLake offers affordable on-demand website development and design.

No matter the size of your project - contact us now, and we'll get it done for you!

Get assistance now

FAQ mode

/

Learning mode

  1. Does "ACF Group Field" and "Field Group" mean the same?

    No, they refer to different concepts. The Field Group is a global container that organizes and displays fields on admin screens, while the Group Field is a local container used within a Field Group to organize related fields together.

  2. Can I have nested groups?

    Yes, you can nest groups within groups. For example, you can have a structure like Group → Repeater → Group, or directly nest groups within each other.

Was this article helpful?

Totally useless

Slightly helpful

Very helpful

Related articles

Content links (69)

About the Author

Maxim Akimov

Certified WordPress expert from Ukraine with over 8 years of experience. Advocate of the BEM methodology and the overall modular approach. Loves sporting activities and enjoys going to the gym and regularly plays table tennis.

0 Comments

    Leave a comment

    Reply to 

    Please be considerate when leaving a comment.

    Not shown publicly


    Got it