I've successfully applied a meta box and checkbox field that can save my settings. However, there is a bit of leftover code that seems to show up on my meta box field.
The checked='checked' shows up correctly in the input checkbox, but it also appears again a standalone preceding the input tag, which I don't want. This is the output:
checked='checked'<input type="checkbox" id="my_meta_box_check1" name="my_meta_box_check1" checked='checked' /><label for="my_meta_box_check1">Do not check this</label>
In my functions.php, I have used the echo output method along with concatenation:
/* Meta Box: Create container */
add_action( 'add_meta_boxes', 'my_meta_box_add' );
function my_meta_box_add() {
add_meta_box( 'my-meta-box', 'Rockwood Options', 'my_meta_box_fields', 'page', 'side', 'high' );
}
/* Meta Box: Create individual fields */
function my_meta_box_fields($post) {
$values = get_post_custom( $post->ID );
$check = isset( $values['my_meta_box_check1'] ) ? esc_attr( $values['my_meta_box_check1'][0] ) : '';
wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' );
echo '<input type="checkbox" id="my_meta_box_check1" name="my_meta_box_check1" ' . checked( $check, "on" ) . ' />';
echo '<label for="my_meta_box_check1">Do not check this</label>';
}
/* Meta Box: Save fields */
add_action( 'save_post', 'my_meta_box_save' );
function my_meta_box_save( $post_id ) {
// Bail if we're doing an auto save
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
// if our nonce isn't there, or we can't verify it, bail
if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) return;
// if our current user can't edit this post, bail
if( !current_user_can( 'edit_post', $post_id ) ) return;
// This is purely my personal preference for saving check-boxes
$chk = isset( $_POST['my_meta_box_check1'] ) && $_POST['my_meta_box_check1'] ? 'on' : 'off';
update_post_meta( $post_id, 'my_meta_box_check1', $chk );
}
I suspect I'm applying the concatenation incorrectly. Anyone have any tips on this?