Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Adding Meta Boxes
/*
3 steps
1. Create the meta field
2. Display is in the admin area
3. Add a save feature that checks the nonce created in the display function
*/
// add homepage meta box
function add_home_awesome_box() {
if( in_array($_GET['post'], array('17') ) ) { // if the page id is in this array
add_meta_box('home_awesome_text', 'Awesome Text Section', 'show_home_awesome_in_admin', 'page');
} // end if in array
}
add_action('add_meta_boxes', 'add_home_awesome_box');
// show that home meta box on the homepage
function show_home_awesome_in_admin($post) {
$valueHomeAwesome = get_post_meta($post->ID, '_home_awesomeness_value', true);
wp_nonce_field( basename( __FILE__ ), 'home_awesome_nonce_field');
?>
<label for="home_awesome_text">Your awesome text will go here</label>
<input type="text" name="home_awesome_text" value="<?php echo $valueHomeAwesome; ?>" />
<?php
} // end showing home awesome only on homepage
// save home meta box
function save_my_awesome_text_box($post_id) {
$isAutosave = wp_is_post_autosave($post_id);
$isRevision = wp_is_post_revision($post_id);
$isValidNonce = false;
if ( isset( $_POST[ 'home_awesome_nonce_field' ] ) ) { // if the nonce is set in the post
if (wp_verify_nonce($_POST['home_awesome_nonce_field'], basename( __FILE__ ))) { // check if valid nonce
$isValidNonce = true;
}
}
// dont save if autosave, revision, or is nonce is false
if ($isAutosave || $isRevision || !$isValidNonce) {
return; // end this function
}
// if the key exists
if (array_key_exists('home_awesome_text', $_POST)) { // check if it is in the save post data
update_post_meta ($post_id, '_home_awesomeness_value', sanitize_text_field($_POST['home_awesome_text']) );
}
} // end save my aweome meta box
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.