Skip to content

Instantly share code, notes, and snippets.

@shohag-biswas
Created February 6, 2018 16:01
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 shohag-biswas/aac4dc988413c2a9aeb7b0931e040420 to your computer and use it in GitHub Desktop.
Save shohag-biswas/aac4dc988413c2a9aeb7b0931e040420 to your computer and use it in GitHub Desktop.
This is how to add metabox in WordPress page or post
<?php
/*
check out the full tuts: https://www.ministryofwp.com/how-to-add-wordpress-meta-box/
*/
function add_guest_details() {
add_meta_box('guest-details', 'Guest details', 'guestcallback', 'post', 'side', 'high');
}
add_action('add_meta_boxes', 'add_guest_details');
function guestcallback($post) {
wp_nonce_field( 'guest_meta_box', 'guest_nonce' );
$name_value = get_post_meta( $post->ID, '_guest_name', true );
$link_value = get_post_meta( $post->ID, '_guest_link', true );
echo '<label for="guest-name">'. 'Guest Blogger Name' .'</label>';
echo '<input type="text" id="guest-name" name="guest_name" placeholder="Example" value="'.$name_value.'" size="25"/>';
echo '<p class="howto">'. 'Add the name of the Guest' .'</p>';
echo '<label for="guest-link">'. 'Guest website Link' .'</label>';
echo '<input type="text" id="guest-link" name="guest_link" placeholder="http://www.example.com/" value="'.$link_value.'" size="25"/>';
echo '<p class="howto">'. 'Add the link of the website' .'</p>';
}
function save_guest( $post_id ) {
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
if ( ! isset( $_POST['guest_nonce'] ) ) {
return;
}
if ( ! wp_verify_nonce( $_POST['guest_nonce'], 'guest_meta_box' ) ) {
return;
}
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
if ( ! isset( $_POST['guest_name'] ) || ! isset( $_POST['guest_link'] ) ) {
return;
}
$guest_name = sanitize_text_field( $_POST['guest_name'] );
$guest_link = sanitize_text_field( $_POST['guest_link'] );
update_post_meta( $post_id, '_guest_name', $guest_name );
update_post_meta( $post_id, '_guest_link', $guest_link );
}
add_action( 'save_post', 'save_guest' );
/*to show metabox value in post or page*/
$name_value = get_post_meta( $post->ID, '_guest_name', true );
$link_value = get_post_meta( $post->ID, '_guest_link', true );
echo ''.$name_value.'<br/>';
echo $link_value;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment