I created a custom checkbox that when I check, I wish it to display slightly different content (specially special css styling). For some reason it is not functioning properly.
In my functions:
add_action( 'add_meta_boxes', 'add_special_checkbox' );
function add_special_checkbox()
{
add_meta_box( 'special-checkbox', 'Special Box', 'special_checkbox_func', 'post', 'side', 'high' );
}
function special_checkbox_func( $post )
{
$values = get_post_custom( $post->ID );
$check = isset( $values['special_box_check'] ) ? esc_attr( $values['special_box_check'][0] ) : '';
wp_nonce_field( 'my_special_box_nonce', 'special_box_nonce' );
?>
<p>
<input type="checkbox" name="special_box_check" id="special_box_check" <?php checked( $check, 'on' ); ?> />
<label for="special_box_check">Is this post 'special?'</label>
</p>
<?php
}
add_action( 'save_post', 'special_checkbox_save' );
function special_checkbox_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['special_box_nonce'] ) || !wp_verify_nonce( $_POST['special_box_nonce'], 'my_special_box_nonce' ) ) return;
// if our current user can't edit this post, bail
if( !current_user_can( 'edit_post' ) ) return;
// now we can actually save the data
$allowed = array(
'a' => array( // on allow a tags
'href' => array() // and those anchords can only have href attribute
)
);
// This is purely my personal preference for saving checkboxes
$chk = ( isset( $_POST['special_box_check'] ) && $_POST['special_box_check'] ) ? 'on' : 'off';
update_post_meta( $post_id, 'special_box_check', $chk );
}
?>
In my loop:
<?php if (get_post_meta($post->ID, 'special_box_check', true)) { ?>
//add special styling
<? } else { ?>
//dont add special styling
<?php } ?>
When I save some posts, they have the special styling even though I did not check the box for them. And when I uncheck a box, I'd like the special styling to go away, but it is not when the box is unchecked.
I am sure I am doing something wrong here. Thanks in advance.