Home > database >  How to retrieve the value of the field in ACF?
How to retrieve the value of the field in ACF?

Time:10-02

        <?php $fields = acf_get_fields('6066'); 
        ?>

<?php if( $fields )
{ 
foreach( $fields as $field)
{
    $value = get_field( $field['name'] );

    if ($value) {
    
        echo '<dl>';
            echo '<dt>' . $field['label'] . '</dt>';
            echo '<dd>' . $field['value'] . '</dd>';
        echo '</dl>';
    }
} 

} 
?>

This is what I have. If I do a var_dump on acf_get_fields, it apparently sets the value to NULL. I could have known, as it's written here:

https://www.advancedcustomfields.com/resources/get_field_object/

The problem: I have to first get all fields in a specific field_group, hence I am using acf_get_fields.

I thought with using $field['value'] I could get it to work, but apparently this does not work.

Can someone help me to retrieve the values in the foreach per field? Surely there must be a way?

PS:

<?php 

$fields = get_fields();

if( $fields ): ?>
    <ul>
        <?php foreach( $fields as $name => $value ): ?>
            <li><b><?php echo $name; ?></b> <?php echo $value; ?></li>
        <?php endforeach; ?>
    </ul>
<?php endif; ?>

This gives me ALL fields. I just need a specific list of fields from a specific field group. That is the problem.

CodePudding user response:

Think the value is always NULL because you're getting it only the group fields, not the fields from a post. Have made a few examples maybe this will help you out.

$post_id  = 123;
$group_id = 1234;

// Get post fields
$post_fields = get_fields($post_id);

foreach ($post_fields as $key => $value) {
    if ($key == 'my_custom_field') {
        echo $value;
    }
}

// Get group fields
$group_fields = acf_get_fields($group_id);
foreach ($group_fields as $key => $group_field) {
    if ($key == 'my_custom_field') {
        echo $value;
    }
}

// Get field objects
$field_objects = get_field_objects($post_id);

foreach ($field_objects as $key => $field_object) {
    if ($key == 'my_custom_field') {
        echo $field_object['value'];
    }
    if ($field_object['name'] == 'my_custom_field') {
        echo $field_object['value'];
    }
    // only show fields from specific group
    if ($field_object['parent'] == $group_id) {
        echo $field_object['value'];
    }
}

CodePudding user response:

<?php 

$fields = get_field('fieldname'); 
        
foreach( $fields as $field)
{
   
echo '<dl>';
            
            echo '<dd>' . $field . '</dd>';
        echo '</dl>';
    }

?>
  • Related