I have this custom field with the name "en_proceso_class" and the value "en_proceso". It was supposed to add a class to a div element in my post query. I was able to do so thanks to Pako Adrian who helped me to add the class to my div code
// Get post meta that is already set
$custom_values = get_post_meta($post->ID, 'en_proceso_class', true);?>
<div class="postthumbnail <?php echo $custom_values; ?>">
But the problem is that if you are on a new post and the custom name "en_proceso_class" is there but the value is empty, I don't want the client to add anything to the class since it's already styled. I thought it's best to convert this into a checkbox. It would be something like "Please check if you want the post to be in process" which will add the class to the post. I did research and again was confused by all those researching... Text field were simple but checkboxes were complicated and it wasn't clear on how I can add the custom field name and value to the checkbox.
Here's the code that I thought should be working? But it wasn't working even after I checked the box and updated it, it still remained unchecked.
add_action( 'add_meta_boxes', 'cd_meta_box_add' );
function cd_meta_box_add()
{
add_meta_box( 'my-meta-box-id', 'My First Meta Box', 'cd_meta_box_cb', 'post', 'normal', 'high' );
}
function cd_meta_box_cb()
{
// $post is already set, and contains an object: the WordPress post
global $post;
$values = get_post_custom( $post->ID );
$text = isset( $values['my_meta_box_text'] ) ? $values['my_meta_box_text'] : '';
$check = isset( $values['en_proceso'] ) ? esc_attr( $values['en_proceso'] ) : '';
// We'll use this nonce field later on when saving.
wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' );
?>
<p>
<input type="checkbox" id="en_proceso_class" name="en_proceso_class" <?php checked( $check, 'on' ); ?> />
<label for="en_proceso_class">Please check if this is in process</label>
</p>
<?php
}
add_action( 'save_post', 'cd_meta_box_save' );
function cd_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' ) ) return;
// now we can actually save the data
$allowed = array(
'a' => array( // on allow a tags
'href' => array() // and those anchors can only have href attribute
)
);
// This is purely my personal preference for saving check-boxes
$chk = isset( $_POST['en_proceso_class'] ) && $_POST['my_meta_box_select'] ? 'on' : 'off';
update_post_meta( $post_id, 'en_proceso_class', $chk );
}
Aucun commentaire:
Enregistrer un commentaire