Enter your keyword

Blog

How to add radio button Metabox in WordPress Custom and Default Post Types

add_action( 'add_meta_boxes', 'post_disable_enable' );
function post_disable_enable() {
add_meta_box('post_disable_enable', 'Post Disable Enable', 'post_disable_enable_meta', 'post' );
}
function post_disable_enable_meta( $post ) {
	wp_nonce_field( 'post_disable_enable', 'post_disable_enable_nonce' );
	$value = get_post_meta( $post->ID, 'post_disable_enable', true );
	echo '<input type="radio" name="post_disable_enable" value="disable" ';
    	if($value=='disable') {
			echo 'checked';
		}
	'> Disable<br/>';
	echo '<input type="radio" name="post_disable_enable" value="enable" ';
		if($value=='enable') {
			echo 'checked';
		}
	echo '> Enable<br/>';
  }
  
add_action( 'save_post', 'disable_enable_save_meta_box_data' );
function disable_enable_save_meta_box_data( $post_id ) {
	// Check if our nonce is set.

	if ( !isset( $_POST['post_disable_enable_nonce'] ) ) {
  	return;
  	}
	// Verify that the nonce is valid.
	if ( !wp_verify_nonce( $_POST['post_disable_enable_nonce'], 'post_disable_enable' ) ) {
	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 ( !current_user_can( 'edit_post', $post_id ) ) {
	return;
	}
  	// Sanitize user input.
  	$new_meta_value = ( isset( $_POST['post_disable_enable'] ) ? sanitize_html_class( $_POST['post_disable_enable'] ) : '' );
	// Update the meta field in the database.
	update_post_meta( $post_id, 'post_disable_enable', $new_meta_value );
  }

No Comments

Add your review

Your email address will not be published.

* Feilds are Required.