Freddy
Freddy

Reputation: 867

Obtaining fields from within ACF group as vars

I'm trying to obtain values from an ACF group but unable to obtain them through two approaches:

Here is how my ACF fields are set up for reference:

enter image description here

Approach 1:

<?php

$welcome_screen_content = get_field('welcome_screen_content'); // type: group

if( $welcome_screen_content ):
  $title = get_field('title');
endif;


echo $title; // prints nothing

?>

Approach 2:

<?php

if( have_rows('welcome_screen_content') ):
  while( have_rows('welcome_screen_content') ): the_row();

  $title = get_sub_field('title');

  echo $title; // prints nothing

  endwhile;
endif;

?>

On my post template, title does have a value:

enter image description here

So unsure why in both attempts, echoing $title does nothing?

Upvotes: 2

Views: 2523

Answers (2)

davemac
davemac

Reputation: 163

I came across this helper function to get values from a field group and found it handy.

You use it like so: get_group_field( '{group field name}', '{sub field name}' );

Upvotes: 0

Lasse
Lasse

Reputation: 1656

When using get_field on a group, Advanced Custom Fields returns an associative array containing the group's fields. So to get the title inside, you do this:

$welcome_screen_content = get_field('welcome_screen_content'); // type: group

if( $welcome_screen_content ):
  $title = $welcome_screen_content['title'];
endif;

Approach 1 doesn't work as expected because get_field('title') asks ACF to get a field at the same level as the "welcome_screen_content" group.

Approach 2 doesn't work as expected because get_subfield is for use with Repeater or Flexible Content Fields.

Upvotes: 5

Related Questions