neilgee
7/16/2017 - 7:01 AM

WordPress Checkbox Metabox in Post Editor Screen - Added as a Plugin

WordPress Checkbox Metabox in Post Editor Screen - Added as a Plugin

<?php

/*
Plugin Name: Checkbox Meta
Plugin URI: http://wpbeaches.com/
Description: Checkbox Test
Author: Neil Gee
Version: 1.0.0
Author URI: http://wpbeaches.com
License: GPL-2.0+
License URI: http://www.gnu.org/licenses/gpl-2.0.txt
Text Domain: checkbox-meta
Domain Path: /languages/
@link  http://themefoundation.com/wordpress-meta-boxes-guide/
@ link https://www.sitepoint.com/adding-custom-meta-boxes-to-wordpress/
*/

/**
 *  Metabox markup per post/page
 *
 * @since 1.2.0
 */

function meta_box_markup($post) {
  wp_nonce_field(basename(__FILE__), "checkbox_nonce");
   $checkbox_stored_meta = get_post_meta( $post->ID );

  ?>

  <label for="_checkbox_check">
 <input type="checkbox" name="_checkbox_check" id="_checkbox_check" value="yes" <?php if ( isset ( $checkbox_stored_meta ['_checkbox_check'] ) ) checked( $checkbox_stored_meta['_checkbox_check'][0], 'yes' ); ?> />
    <?php _e( 'Disable Checkbox', 'checkbox-meta' )?>
  </label>

  <?php

}

/**
 *  Save metabox markup per post/page
 *
 * @since 1.2.0
 */

function save_custom_meta_box( $post_id ) {
  // Checks save status
 $is_autosave = wp_is_post_autosave( $post_id );
 $is_revision = wp_is_post_revision( $post_id );
 $is_valid_nonce = ( isset( $_POST[ 'checkbox_nonce' ] ) && wp_verify_nonce( $_POST[ 'checkbox_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';

 // Exits script depending on save status
   if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
       return;
   }


 // Checks for input and saves
  if( isset( $_POST[ '_checkbox_check' ] ) ) {
      update_post_meta( $post_id, '_checkbox_check', 'yes');
  }
  else {
      update_post_meta( $post_id, '_checkbox_check', '' );
  }
}
add_action('save_post', 'save_custom_meta_box', 10, 2);


/**
 *  Add Metabox per post/page and any registered custom post type
 *
 * @since 1.2.0
 */
function add_custom_meta_box() {

    $post_types = get_post_types();
   foreach ( $post_types as $post_type ) {
    add_meta_box('checkbox-meta-box', __('Disable Checkbox', 'checkbox-meta'), 'meta_box_markup', $post_types, 'side', 'default', null);
   }
}
add_action('add_meta_boxes', 'add_custom_meta_box');