We can get the categories via get_categories() function (which will get the same categories as wp_dropdown_categories() function), but as array and without the markup.
As the value is returned as array, we can loop through the categories and generate the HTML ourself.
Usually, we would aim for a structure like this:
<select name="categories">
<option value="1">Category 1</option>
<option value="2">Category 2</option>
<option value="3">Category 3</option>
</select>
So we're going to generate the structure from above via PHP by looping through the $categories
array:
echo '<select name="categories">';
// Get categories as array
$categories = get_categories( $args );
foreach ( $categories as $category ) :
echo '<option value="' . $category->term_id . '">' . $category->name . '</option>';
endforeach;
echo '</select>';
Feel free to modify the function via the $args
parameters (see Codex for reference).
Now we'll just need to add the selected
attribute within the <option>
, so we're going to add this via a short if statement to compare the current $category->term_id
and the one saved in the database $stored_category_id
:
$stored_category_id = 10; // This is the value from the database
$selected = ( $stored_category_id == $category->term_id ) ? 'selected' : '';
And that's it! Your complete snippet (maybe with a default option at the beginning) should now look something like this:
echo '<select name="categories">';
// Add custom option as default
echo '<option>' . __('No Category', 'text-domain') . '</option>';
// Get categories as array
$categories = get_categories( $args );
foreach ( $categories as $category ) :
// Check if current term ID is equal to term ID stored in database
$selected = ( $stored_category_id == $category->term_id ) ? 'selected' : '';
echo '<option value="' . $category->term_id . '" ' . $selected . '>' . $category->name . '</option>';
endforeach;
echo '</select>';
Good luck! :)
selected
within theoption