Skip to content

Instantly share code, notes, and snippets.

@devfaysal
Created October 25, 2017 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devfaysal/2721479664a54ec061a8319e2753c0d3 to your computer and use it in GitHub Desktop.
Save devfaysal/2721479664a54ec061a8319e2753c0d3 to your computer and use it in GitHub Desktop.
Sample code for adding metabox to wordpress
/**
* Adding Metabox for adding a checkbox to hide or unhide the page title
*/
function fay_add_meta_box_for_page_title_display()
{
add_meta_box( 'fay-meta-box-for-page-title', 'Page Title', 'fay_add_meta_box_for_page_title_display_callback', 'page', 'side', 'high' );
}
add_action( 'add_meta_boxes', 'fay_add_meta_box_for_page_title_display' );
function fay_add_meta_box_for_page_title_display_callback($post){
//Get the valu of the metbox
$fay_meta_box_for_page_title_display = get_post_meta( $post->ID, '_fay_page_title_display', true );
//Checkbox display hepler
$fay_meta_box_for_page_title_display = $fay_meta_box_for_page_title_display == 'hide' ? 'checked' : '';
wp_nonce_field( 'fay_meta_box_for_page_title_display_nonce', 'fay_meta_box_nonce' );
echo '<input type="checkbox" id="fay_meta_box_for_page_title_display" name="fay_meta_box_for_page_title_display" value="hide" '.esc_attr($fay_meta_box_for_page_title_display).'/>';
echo '<label for="fay_meta_box_for_page_title_display">Hide title of this page?</label>';
}
function fay_meta_box_for_page_title_display_nonce ($post_id){
// Exit if doing an auto save
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
// if nonce isn't there, or can't verify it, exit
if( !isset( $_POST['fay_meta_box_nonce'] ) || !wp_verify_nonce( $_POST['fay_meta_box_nonce'], 'fay_meta_box_for_page_title_display_nonce' ) ) return;
// if current user can't edit this post, exit
if( !current_user_can( 'edit_post' ) ) return;
$data = $_POST['fay_meta_box_for_page_title_display'];
update_post_meta($post_id, '_fay_page_title_display', $data);
}
add_action('save_post','fay_meta_box_for_page_title_display_nonce');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment