如何设置默认复选框中选中的默认复选框

问题描述 投票:0回答:1

我知道这个问题已经出现很多次了,但是我找不到答案。我有一个简单的复选框,并且一切正常,除了默认值始终为空。这是我的代码:

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 );

默认情况下如何通过检查?我在做什么错?

谢谢。

wordpress wordpress-theming meta-boxes
1个回答
0
投票

执行以下操作:

<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; ?> />
© www.soinside.com 2019 - 2024. All rights reserved.