Last active
May 1, 2020 00:02
-
-
Save Jahid07/b3a4cc0363aa42ef052aa9748df49b89 to your computer and use it in GitHub Desktop.
WordPress custom metabox for custom post type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Contact meta boxex | |
* Custom post type name is "prefix-contact" | |
*/ | |
function prefix_contact_add_meta_box() | |
{ | |
add_meta_box( 'contact_email', 'User Email', 'prefix_contact_email_callback', 'prefix-contact', 'side', 'low'); | |
} | |
/** | |
* Generate Html For the cutom Metabox | |
* @param $post | |
*/ | |
function prefix_contact_email_callback($post) | |
{ | |
wp_nonce_field( 'prefix_save_conatact_email_data', 'prefix_contact_email_meta_box_nonce'); | |
$value = get_post_meta( $post->ID, '_contact_email_value_key', true ); | |
echo '<label for="prefix_contact_email_field"> User Email Address</lable>'; | |
echo '<input type="email" id="prefix_contact_email_field" name="prefix_contact_email_field" value="'. esc_attr( $value ) .'" size="25">'; | |
} | |
/** | |
* Validate & Save data for the custom metabox | |
* @param $post_id | |
*/ | |
add_action( 'save_post', 'prefix_save_conatact_email_data'); | |
function prefix_save_conatact_email_data($post_id) | |
{ | |
//Validate if the wordpress nonce is exsit | |
if(!isset($_POST['prefix_contact_email_meta_box_nonce'])) | |
{ | |
return; | |
} | |
// Varify WordPress nonce | |
if(!wp_verify_nonce( $_POST['prefix_contact_email_meta_box_nonce'], 'prefix_save_conatact_email_data' )) | |
{ | |
return; | |
} | |
// Skip Auto save | |
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) | |
{ | |
return; | |
} | |
// Validate if the curent user can edit the post | |
if(!current_user_can( 'edit_post', $post_id )) | |
{ | |
return; | |
} | |
// Validate if the filed is not empty | |
if(!isset($_POST['prefix_contact_email_field'])){ | |
return; | |
} | |
$email_data = sanitize_text_field($_POST['prefix_contact_email_field']); //Sanitize the filed | |
update_post_meta( $post_id, '_contact_email_value_key', $email_data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment