multicheck box for post metabox

I took the example code you suggested and changed the following to get multicheck support:

// Add this at the end of the file
// A good prefix for your name prevents problems later!
function wpse6513_get_meta_check( $args = array(), $current_values = array() )
{
    extract( $args );

    $name_esc = esc_attr( $name );

    if ( ! is_array( $current_values ) ) {
        $current_values = array();
    }

    echo '<tr>';
    echo '<th style="width: 10%">';
    echo '<label for="' . $name_esc . '">' . esc_html( $title ) . '</label>';
    echo '</th>';
    echo '<td>';

    foreach ( $options as $option_value => $option_label ) {
        $option_value_esc = esc_attr( $option_value );
        echo '<label><input type="checkbox" name="' . $name_esc . '[]" id="' . $name_esc . '_' . $option_value_esc . '" value="' . $option_value_esc . '"';
        if ( in_array( $option_value, $current_values ) ) {
            echo ' checked="checked"';
        }
        echo '/> ' . esc_html( $option_label );
        echo '</label><br/>';
    }
    echo '<input type="hidden" name="' . $name_esc . '_noncename" id="' . $name_esc . '_noncename" value="' . wp_create_nonce( plugin_basename( __FILE__ ) ) . '" />';

    echo '</td>';
    echo '</tr>';
}

In hybrid_save_meta_data():

// Replace this line:
$data = stripslashes( $_POST[$meta_box['name']] );
// By these lines:
$data = array_key_exists( $meta_box['name'], $_POST ) ? $_POST[$meta_box['name']] : '';
if ( is_array( $data ) ) {
    $data = array_map( 'stripslashes', $data );
} else {
    $data = stripslashes( $data );
}

And of course, in post_meta_boxes():

// Add this to the `$meta['type']` if/else list
elseif ( $meta['type'] == 'check' )
    wpse6513_get_meta_check( $meta, $value );

Now you can handle “multichecks” of the form you suggested:

'location' => array(
    'name' => 'location',
    'title' => __('Location:', 'hybrid'),
    'type' => 'check',
    'options' => array(
        'AL' => 'Alabama',
        'CA' => 'California',
        'DE' => 'Delaware',
    ),
),

Finally some code to prevent warnings (which you won’t see unless you enable WP_DEBUG):

// Replace all `wp_specialchar()` calls with `esc_attr()`
// Add these lines in `hybrid_save_meta_data()`:
// At the start, after `global $post`:
if ( ! array_key_exists( 'post_type', $_POST ) ) {
    return $post_id;
}

// In the foreach loop, instead of:
if ( !wp_verify_nonce( $_POST[$meta_box['name'] . '_noncename'], plugin_basename( __FILE__ ) ) )
    return $post_id;
// Write:
$nonce_name = $meta_box['name'] . '_noncename';
if ( ! array_key_exists( $nonce_name, $_POST ) || !wp_verify_nonce( $_POST[$nonce_name], plugin_basename( __FILE__ ) ) )
    return $post_id;

Leave a Comment