0

Specifically, I am using the add_image_attachment_fields_to_edit function. I have my declaration of label, input..

$form_fields["custom4"]["label"] = __("Custom Select");
$form_fields["custom4"]["input"] = "html";

But when I try to iterate through my categories for the select, I get errors, or an empty html select. So far I have..

$form_fields["custom4"]["html"] = "
<select name='attachments[{$post->ID}][custom4]' id='attachments[{$post->ID}][custom4]'>" .
    foreach ($categories as $category) {
        return "<option value=$category>$category</option>";
    } . "
</select>";

Is it possible to run a foreach loop within the $form_fields assignment, how can I create an html select constructed with my category names?

0

The way you're appending a foreach loop to a variable is not possible.

Try this:

$form_fields["custom4"]["html"] = "<select name='attachments[{$post->ID}][custom4]' id='attachments[{$post->ID}][custom4]'>";

foreach ($categories as $category) {
     $form_fields["custom4"]["html"] .= '<option value="$category">' . $category . '</option>';
}

$form_fields["custom4"]["html"] .= "</select>";
|improve this answer|||||
  • No error on this, but the media popup doesn't load. imgur.com/Y8wokq6 – Chris Jan 14 '15 at 20:55
  • Can you provide a bit more information or the surrounding code? Is the developer tools showing any errors in the console? And have you tried enabling developer mode to check if there are php errors? – Sjors Roelofs Jan 14 '15 at 21:17
  • No errors in chrome dev tools, the entirety of the code in my functions.php is pastebin.com/D0FzSkWC – Chris Jan 14 '15 at 21:22
0

Hmm, I see you're using the get_categories() function to retrieve all categories. That function is returning an array with category objects.

This means you have to edit the foreach loop, because $category is an object.

$form_fields["custom4"]["html"] .= '<option value="' . $category->term_id . '">' . $category->name . '</option>';

Have you enabled the debug mode in WordPress? It will show you errors in your php code. Have a look at http://codex.wordpress.org/Debugging_in_WordPress


I also think your save function isn't working. You're using 'restaurant', but your input has the name 'custom4'.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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