0

I'm trying to access the values of a ACF sub field using PHP.

$articles = get_posts(
 array(
  'posts_per_page' => -1,
  'post_status' => 'publish',
  'post_type' => array('venues', 'suppliers'),
 )
);


$locations = array();
foreach ($articles as $article) {

    $field = get_field('info_items', $article->ID, false);

    if( have_rows('info_items') ):
        while( have_rows('parent_field') ): the_row();

        $value = get_sub_field('info_location');

        endwhile;

    endif;
    var_dump($value);
    exit();
}

In the code above if I var_dump the contents of $field I get the array showing all the subfields - including the one I want:

array(3) { [0]=> array(2) { ["acf_fc_layout"]=> string(13) "info_location" ["field_59ea62cf04adf"]=> string(16) "Manchester" } [1]=> array(2) { ["acf_fc_layout"]=> string(10) "info_phone" ["field_59ea634904ae3"]=> string(11) "08009788221" } [2]=> array(3) { ["acf_fc_layout"]=> string(12) "info_website" ["field_59ea635c04ae5"]=> string(32) "https://www.stuffandstuff.co.uk" ["field_5c6802013bb34"]=> string(0) "" } } NULL

I'm trying to retrieve the 'info_location' value - in this example the string 'Manchester'.

The have_rows loop is from the ACF website docs for get_sub_field but doesn't work in this context.

1
  • 1
    Check while loop in your code. You need to pass parent field there. Dec 30, 2019 at 13:30

1 Answer 1

1

You iterate through posts obtained by the get_posts(), so you have to pass post ID as the second parameter of the function have_rows(). By default ID of current post is used.

foreach ($articles as $article) {

    $value = null;
    if( have_rows( 'info_items', $article->ID ) ): 
        while( have_rows( 'info_items', $article->ID ) ): the_row();

            $value = get_sub_field('info_location');

        endwhile;

    endif;

    echo "<br>{$article->ID} ";
    var_dump($value);
}
4
  • Thanks for this - should have seen that. Still getting an issue that it's returning bool(false) where it should be returning Manchester. Any ideas?
    – steve
    Dec 30, 2019 at 13:57
  • Did you change have_rows() on both lines?
    – nmr
    Dec 30, 2019 at 14:01
  • Yes changed both
    – steve
    Dec 30, 2019 at 14:03
  • With your amendment it now prints the article ID and bool(false) for each article. Something very strange going on...
    – steve
    Dec 30, 2019 at 15:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.