I added the meta box to my post page, so that I can choose what layout I have for each post. I created a meta box, and it's showing, but it won't save.
if ( ! function_exists( 'post_layout_meta_box' ) ){
function post_layout_meta_box( $post ){
$custom = get_post_custom($post->ID);
$page_layout = isset($custom["page_layout_left"][0]) ? $custom["page_layout_left"][0] : ( isset($custom["page_layout_right"][0]) ? $custom["page_layout_right"][0] : $custom["page_layout_none"][0] );
?>
<p>
<select name="page_layout" id="page_layout">
<option value="left_sidebar" <?php selected( $page_layout, 'left_sidebar' ); ?>>Left Sidebar</option>
<option value="right_sidebar" <?php selected( $page_layout, 'right_sidebar' ); ?>>Right Sidebar</option>
<option value="full_width" <?php selected( $page_layout, 'full_width' ); ?>>No Sidebar</option>
</select>
</p>
<?php
}
}
if ( ! function_exists( 'post_save_layout_meta_box' ) ){
function post_save_layout_meta_box($post_id){
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ){
return $post_id;
} else{
if( isset( $_POST['page_layout'] ) ) {
update_post_meta( $post_id, 'page_layout', wp_kses($_POST['page_layout'], '') );
}
}
}
}
add_action( 'save_post', 'post_save_layout_meta_box' );
So what am I missing? When I choose Right Sidebar for example, it will return the value to the Left Sidebar after updating a page.
EDIT: Figured it out:
The problem was in this:
$page_layout = isset($custom["page_layout_left"][0]) ? $custom["page_layout_left"][0] : ( isset($custom["page_layout_right"][0]) ? $custom["page_layout_right"][0] : $custom["page_layout_none"][0] );
It should be
$page_layout = isset($custom["page_layout"][0]) ? $custom["page_layout"][0] : 'left_sidebar';
I guess this, in these lines of code there is problem. Wordpress confuse with page_layout_left, page_layout_right.
$page_layout = isset($custom["page_layout_left"][0]) ? $custom["page_layout_left"][0] : ( isset($custom["page_layout_right"][0]) ? $custom["page_layout_right"][0] : $custom["page_layout_none"][0] );
update_post_meta( $post_id, 'page_layout', wp_kses($_POST['page_layout'], '') );
I suggest if you want to use page_layout_left in update_post_meta() function then you should first find what option user selected i.e left or right or full width.
After that in update_post_meta function instead of using page_layout custom field name, use either page_layout_left or page_layout_right like this.
update_post_meta( $post_id, 'page_layout_left', wp_kses($_POST['page_layout'], '') );
Hope it may work.
Happy Coding.
Atul Jindal