0

I'm using a wordpress plugin names "Advanced Custom Fields". Within the admin I have a select field where multiple choices can be selected.

So for example the admin will have the following selected....

/apples-category/ : Read More on apples
/pears-category/ : Read More on pears
/oranges-category/ : Read More on oranges
/peach-category/ : Read More on peaches

The first part which is the value (/apples-category/) will be used within a hyper link. The second part which is the label (Read More on apples) will be the anchor text.

I've put the following together which outputs the following correct labels but for some reason they all have the href (value) of the very last option (/peach-category/)

Read More on apples, Read More on pears, Read More on oranges, Read More on peaches

Here's my code and apologies if it looks obvious, I've just started out coding and still need assistance :)

Hope you can assist.

 <?php
 $labels = array();
 $field = get_field_object('select_fruit');
 $values = get_field('select_fruit');
 foreach ($values as $value) {
 $labels[] = $field['choices'][ $value ];
 }

 foreach ($labels as $k=>$label){
 echo '<a href="'.$value.'" />'.strtoupper($label).'</a>'.($k ==                 count($labels) - 1 ? '' : ', ');
}?>

1 Answer 1

1

Try this code:

<?php
 $fruit_array = array();
 $field = get_field_object('select_fruit');
 if(!empty($field['value']))
 {
     foreach ($field['value'] as $value)
     {
        $fruit_array[$value]=$field['choices'][ $value ];
     }
     $cnt=0;
     foreach ($fruit_array as $fruit_key=>$fruit_value)
     {
        echo '<a href="'.$fruit_key.'" />'.strtoupper($fruit_value).'</a>'.($cnt == count($fruit_array) - 1 ? '' : ', ');
        $cnt++;
     }
 }
?>
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you so much :) It works perfectly. I'm going to study how your code was put together so I know where I went wrong. It looks like I was missing a second foreach for the value.
Just one question if I may... I get the following error on this line.. foreach ($field['value'] as $value).......PHP Warning: Invalid argument supplied for foreach() in..... Any ideas how to fix the warning?
And also the following from the same line..... PHP Warning: Illegal offset type in
For Warning: Invalid argument supplied for foreach() in....you just need to check that $field['value'] array is not empty. I have updated the answer, please check.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.