我为特定页面模板创建了metabox。现在我需要保存复选框的选中或未选中值。我该怎么做?
这是我的代码:
add_action(\'add_meta_boxes\', \'add_home_meta\');
function add_home_meta()
{
global $post;
if(!empty($post))
{
$pageTemplate = get_post_meta($post->ID, \'_wp_page_template\', true);
if($pageTemplate == \'template-home.php\' )
{
add_meta_box(
\'home_meta\', // $id
\'Homepage Options\', // $title
\'display_home_meta\', // $callback
\'page\', // $page
\'normal\', // $context
\'high\'); // $priority
}
}
}
function display_home_meta() {
global $post;
// Add the HTML for the post meta
wp_nonce_field( \'avt_homepage_meta_box\', \'avt_homepage_meta_box_nonce\' );
/*
* Use get_post_meta() to retrieve an existing value
* from the database and use the value for the form.
*/
$value = get_post_meta( $post->ID, \'home_slider_display\', true );
?>
<p>
<label for="avt_slider_slide_url">
<strong><?php _e( \'Display slider on homepage:\', \'avt\' ); ?></strong>
</label>
<input type="checkbox" name="home_slider_display" value="true" />
</p>
<?php }
function avt_homepage_save_meta_box_data( $post_id ) {
// Check if our nonce is set.
if ( ! isset( $_POST[\'avt_homepage_meta_box_nonce\'] ) ) {
return;
}
// Verify that the nonce is valid.
if ( ! wp_verify_nonce( $_POST[\'avt_homepage_meta_box_nonce\'], \'avt_homepage_meta_box\' ) ) {
return;
}
// If this is an autosave, our form has not been submitted, so we don\'t want to do anything.
if ( defined( \'DOING_AUTOSAVE\' ) && DOING_AUTOSAVE ) {
return;
}
// Check the user\'s permissions.
if ( isset( $_POST[\'post_type\'] ) && \'page\' == $_POST[\'post_type\'] ) {
if ( ! current_user_can( \'edit_page\', $post_id ) ) {
return;
}
} else {
if ( ! current_user_can( \'edit_post\', $post_id ) ) {
return;
}
}
/* OK, its safe for us to save the data now. */
// Make sure that it is set.
if ( ! isset( $_POST[\'home_slider_display\'] ) ) {
return;
}
// Sanitize user input.
$my_data = sanitize_text_field( $_POST[\'home_slider_display\'] );
// Update the meta field in the database.
update_post_meta( $post_id, \'home_slider_display\', $my_data );
}
add_action( \'save_post\', \'avt_homepage_save_meta_box_data\' );