WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to display a select dropdown field in the post meta. How can I validate the input before saving it?

Currently, I am simply saving without validating like this:

if ( isset( $_POST['select_meta'] ) ) {     
        update_post_meta( $post->ID, 'select_meta', $_POST['select_meta'] );    
    }

Here's the code I'm using to display the meta field:

$select_items = ('one', 'two', 'three');

$select_meta = get_post_meta( $post->ID, 'select_meta', true ); ?>

<select id="select_meta" name="select_meta">
    <?php
        if($select_items){
            foreach ($select_items as $item){?>
                <option <?php selected( $item == $select_meta ); ?> value="<?php echo $item; ?>"><?php echo $item ?></option>                           
                <?php                   
            }
        }
    ?>      
</select>
share|improve this question

Separate the allowed values in a function:

function get_allowed_values()
{
    return array('one', 'two', 'three');
}

In your metabox:

foreach ( get_allowed_values() as $item) {}

In your validation handler:

if ( isset( $_POST['select_meta'] ) 
    and in_array( $_POST['select_meta'], get_allowed_values() )
)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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