Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

php - Looking to loop through ACF subfields to get label and value without using field_name

I'm looking for an easy way to display prepack sizing distribution for wholesale clothing. So, the product page will display a table with how many pieces of that clothing come in each size. Unfortunately, since I'm new here, I can't upload a picture of my ACF fields but I have an ACF group field and then inside that I have subfields with the size's name(Small, Medium, Large, etc.) and then the value is the number of pieces in that size.

I want to loop through the subfields and echo out the label of the subfield and the value of the subfield so that I can make a table. I don't want to have to use specific subfield names because I want the code to work even if I make changes to the names. Here's what I have so far:

$fields = get_field('lettered_packing'); //my parent field
foreach ($fields as $field) {
    echo $field;
}

Doing this echoes out the value of each subfield but I would also like to be able to echo out the label of each subfield as well. Is this possible?

question from:https://stackoverflow.com/questions/65943770/looking-to-loop-through-acf-subfields-to-get-label-and-value-without-using-field

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I was able to find a solution that worked for me. I'll post it here incase someone else comes across this problem.

So, the trick was creating an array from the get_field_object function to get all subfield names and then using that array when going through the parent field to gain access to both value and label.

$parent_field = get_field_object('your-parent-field-name');
    $fields = array();

    if (count($parent_field['sub_fields'])) {
        foreach ($parent_field['sub_fields'] as $field) {
            $fields[] = $field['name']; 
        }
    }
if( have_rows($parent_field) ):
    while ( have_rows($parent_field) ) : the_row(); 

    foreach ($fields as $sub_field) {
        $field = get_sub_field_object($sub_field);
        
        echo '<span>' . $field['label'] . ':' . $field['value'] . '</span>'; 

    }

I'm not sure if this is the most eloquent solution or not. But it works for now.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...