How to save a checkbox meta box in WordPress?

后端 未结 1 1556
抹茶落季
抹茶落季 2020-12-31 16:09

I\'m trying to add a checkbox into my custom meta box in WordPress and I ran into a problem with saving it - whenever I check the checkbox and update the post/page, it comes

相关标签:
1条回答
  • 2020-12-31 16:58

    I had trouble with this previously and here is how I solved it.

    First, creating the Checkbox.

    <?php
    function sl_meta_box_sidebar(){
        global $post;
        $custom = get_post_custom($post->ID);
        $sl_meta_box_sidebar = $custom["sl-meta-box-sidebar"][0]; 
    ?>
    
    <input type="checkbox" name="sl-meta-box-sidebar" <?php if( $sl_meta_box_sidebar == true ) { ?>checked="checked"<?php } ?> />  Check the Box.
    <?php } ?>
    

    Next, saving.

    <?php
    add_action('save_post', 'save_details');
    
    function save_details($post_ID = 0) {
        $post_ID = (int) $post_ID;
        $post_type = get_post_type( $post_ID );
        $post_status = get_post_status( $post_ID );
    
        if ($post_type) {
        update_post_meta($post_ID, "sl-meta-box-sidebar", $_POST["sl-meta-box-sidebar"]);
        }
       return $post_ID;
    } ?>
    
    0 讨论(0)
提交回复
热议问题