I’m trying to add some settings to my WordPress options page that depend on the number of categories. I created this function to use inside the main array, but it only returns the first array, leaving out the other 3 I have. A print_r
will show all of them, so I can’t seem to figure this out.
function listSections() {
$categories = get_categories();
foreach($categories as $category) {
return array (
"name" => $category->cat_name . " Label Color",
"desc" => "Select a label color.",
"id" => $shortname."_label_color" . $category->cat_ID,
"type" => "select",
"options" => $color_options,
"std" => ""
);
}
}
You can only return once!
The fix is push each array into a temporary array, then return that array at the end of the loop.
The function can only return once. It cannot return multiple things in a loop. After it reaches the first return, it exits the function completely. If you want to return an array of arrays, you should use the following.
using the syntax $result[] = xyz; will append xyz to the end of the array. You can loop through the returned array, with some code like
When you call
return
from a function it always immediately ends the execution of that function, so as soon as the first array gets returned, the function ends – which is why you are only getting the first array back.You could try returning a multi-dimensional array (an array that contains all of the arrays you’d like to be returned) instead.
The goal of the
return
keyword is to exit the function. So it is normal that your fonction only return the first element.You can for exemple put all the elements into an array and return this array :