Creating a Dropdown Custom Meta Field in WordPress


Here’s a helpful snippet. Let’s say you want to add a State dropdown as a custom meta field on a post, page or custom post type. It can be kind of a pain but if you add the names and values as key value pairs you can loop through the array and output the HTML pretty easily.

First get the value of _cpt_state (if it has one) and assign it to $state
[php]if ( ! $state = get_post_meta( $post->ID, ‘_cpt_state’, true ) ) $state = ”;[/php]

Then insert the below code (all of which is called by the add_meta_box() function). This code will loop through the array of states key/value pairs and echo the HTML pair. Then once the User Admin returns to the Edit Post page the previously saved State will be auto selected.

[php]<label for=”_cpt_state”>State:</label><br />
<select name=”_cpt_state” id=”_cpt_state” class=”widefat” >
<?php
$states = array(
‘AL’ => ‘Alabama’,
‘AK’ => ‘Alaska’,
‘AZ’ => ‘Arizona’,
‘AR’ => ‘Arkansas’,
‘CA’ => ‘California’,
‘CO’ => ‘Colorado’,
‘CT’ => ‘Connecticut’,
‘DE’ => ‘Delaware’,
‘DC’ => ‘District of Columbia’,
‘FL’ => ‘Florida’,
‘GA’ => ‘Georgia’,
‘HI’ => ‘Hawaii’,
‘ID’ => ‘Idaho’,
‘IL’ => ‘Illinois’,
‘IN’ => ‘Indiana’,
‘IA’ => ‘Iowa’,
‘KS’ => ‘Kansas’,
‘KY’ => ‘Kentucky’,
‘LA’ => ‘Louisiana’,
‘ME’ => ‘Maine’,
‘MD’ => ‘Maryland’,
‘MA’ => ‘Massachusetts’,
‘MI’ => ‘Michigan’,
‘MN’ => ‘Minnesota’,
‘MS’ => ‘Mississippi’,
‘MO’ => ‘Missouri’,
‘MT’ => ‘Montana’,
‘NE’ => ‘Nebraska’,
‘NV’ => ‘Nevada’,
‘NH’ => ‘New Hampshire’,
‘NJ’ => ‘New Jersey’,
‘NM’ => ‘New Mexico’,
‘NY’ => ‘New York’,
‘NC’ => ‘North Carolina’,
‘ND’ => ‘North Dakota’,
‘OH’ => ‘Ohio’,
‘OK’ => ‘Oklahoma’,
‘OR’ => ‘Oregon’,
‘PA’ => ‘Pennsylvania’,
‘RI’ => ‘Rhode Island’,
‘SC’ => ‘South Carolina’,
‘SD’ => ‘South Dakota’,
‘TN’ => ‘Tennessee’,
‘TX’ => ‘Texas’,
‘UT’ => ‘Utah’,
‘VT’ => ‘Vermont’,
‘VA’ => ‘Virginia’,
‘WA’ => ‘Washington’,
‘WV’ => ‘West Virginia’,
‘WI’ => ‘Wisconsin’,
‘WY’ => ‘Wyoming’
);
$selected = esc_attr( $state );
foreach ($states as $code => $label) {
echo ‘<option value=”‘.$code.’”‘;
if ($selected == $code) {
echo ‘ selected=”selected”‘;
}
echo ‘>’ . $label . ‘</option>’;
}
?>
</select>
[/php]


2 responses to “Creating a Dropdown Custom Meta Field in WordPress”

  1. Hello!

    I’ve added this code to my custom meta box, but whenever I save the post, the State doesn’t save, and reverts back to Alabama. Is there something I’m missing?

    Thanks,
    Alexandra

    • Did you create and use a save_post function? The code above is for adding the required html for the form field in the meta, not saving it. All WP Post meta needs to be displayed as a form element and needs another function to save it.

Leave a Reply

Your email address will not be published. Required fields are marked *