0

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>

1 Answer 1

2

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() )
)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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