Last active
December 7, 2017 09:45
-
-
Save humayunahmed8/a60e1a284101ed58a5a0aa0d4eacbacd to your computer and use it in GitHub Desktop.
Register custom meta boxes
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
// Register a meta box under the services section | |
function service_meta_box() { | |
add_meta_box( | |
'service_icon',//id | |
'Service Metabox',//title | |
'service_icon_callback',//callback | |
'service',//screen | |
'side',//context | |
'high'//priority | |
); | |
// $screen = array('post' , 'team' , 'page' , 'service'); | |
} | |
add_action('add_meta_boxes','service_meta_box'); | |
function service_icon_callback($post) { | |
//input type value call as a variable (input box name is "s_icon") | |
$s_icon = get_post_meta($post->ID,'s_icon',true); | |
//wp_nonce_field('action','name', '$referer', '$echo'); | |
//The nonce field is used to validate that the contents of the form request came from the current site and not somewhere else. | |
wp_nonce_field('save_service_meta','service_nonce'); | |
?> | |
<p> | |
<label for="">Icon</label> | |
<input type="text" name="s_icon" value="<?php echo $s_icon; ?>"> | |
</p> | |
<?php | |
} | |
function save_service_meta($post_id) { | |
// check if our nonce is set. | |
if(! isset($_POST ['service_nonce'])){ | |
return; | |
} | |
// verify that the nonce is valid. | |
if (! wp_verify_nonce($_POST['service_nonce'], 'save_service_meta')) { | |
return; | |
} | |
// make sure that the input box is set. | |
if (! isset($_POST['s_icon'])) { | |
return; | |
} | |
// sanitize user input | |
$my_s_icon = sanitize_text_field($_POST['s_icon']); | |
// update the meta filed in the database. | |
update_post_meta($post_id, 's_icon' , $my_s_icon); | |
} | |
add_action('save_post','save_service_meta'); |
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
There are three steps of working metabox: | |
========================================= | |
1. First Function ===> Add Meta Box | |
2. Second Function ===> Callback ==> HTML Rendering | |
3. Third Function ===> Save Meta Box Data | |
1. Meta Box Add | |
2. Data Rendering | |
3. Data save process: | |
3.1 ==> Nonce set | |
3.2 ==> Nonce validation check | |
3.3 ==> Confirm nonce option | |
3.4 ==> Sanitize Data | |
3.5 ==> Update Data with Id | |
4. Usage of Custom Meta Box: | |
============================== | |
<div class="icon"> | |
<i class="fa fa-<?php echo get_post_meta($post->ID,'s_icon',true); ?>"></i> | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment