我知道这个问题出现了很多次, 但是我找不到答案。我有一个简单的复选框, 并且一切正常, 除了默认值始终为空。这是我的代码:
function portfolio_additional_settings($post) {
$meta_port_cats = get_post_meta($post->ID, '_portfolio_meta_cats', true);
wp_nonce_field( 'update_portfolio_additional_settings', 'update_portfolio_additional_nonce' );
?>
<div>
<input type="checkbox" name="portfolio_meta_cats_field" id="portfolio_meta_cats_field" value="1" <?php checked($meta_port_cats, 1); ?> />
<label for="portfolio_meta_cats_field"><?php esc_html_e( 'Categories', 'portfolio' ); ?></label>
</div>
}
function save_portfolio_additional_settings($post_id, $post) {
$edit_cap = get_post_type_object( $post->post_type )->cap->edit_post;
if( !current_user_can( $edit_cap, $post_id )) {
return;
}
if( !isset( $_POST['update_portfolio_additional_nonce']) || !wp_verify_nonce( $_POST['update_portfolio_additional_nonce'], 'update_portfolio_additional_settings' )) {
return;
}
if(array_key_exists('portfolio_meta_cats_field', $_POST)) {
update_post_meta(
$post_id, '_portfolio_meta_cats', sanitize_text_field($_POST['portfolio_meta_cats_field'])
);
} else {
update_post_meta(
$post_id, '_portfolio_meta_cats', null);
}
}
add_action( 'save_post', 'save_portfolio_additional_settings', 10, 2 );
默认情况下如何通过检查?我究竟做错了什么?
谢谢。
#1
进行如下操作:
<input type="checkbox"
name="portfolio_meta_cats_field"
id="portfolio_meta_cats_field"
value="<?php echo $meta_port_cats; ?>"
<?php if ($meta_port_cats === '1'): ?>checked<?php endif; ?> />
评论前必须登录!
注册