Posted on September 28, 2015
function wpsnipp_add_subtitle_metabox() {
add_meta_box(
'wpsnipp-subtitle', // Box ID
__( 'Post Subtitle' ), // Box Title
'wpsnipp_render_subtitle_metabox', // Callback function
'post', // Post-type
'normal', // Context
'high' // Priority
);
}
add_action( 'add_meta_boxes', 'wpsnipp_add_subtitle_metabox' );
function wpsnipp_render_subtitle_metabox() {
// Add an nonce field for security.. we'll verify it later when saving the data
wp_nonce_field( 'wpsnipp_subtitle_metabox', 'wpsnipp_subtitle_metabox_nonce' );
// Retrieve the existing value (if any) to display in the field.
$subtitle = get_post_meta( get_the_ID(), 'wpsnipp_post_subtitle', true );
// Add our input field
?>
<p><input type="text" class="widefat" id="wpsnipp-subtitle" name="wpsnipp-subtitle" value="<?php echo esc_attr( $subtitle ); ?>" /></p>
<?php
}
// $post_id is passed into the function for us
function wpsnipp_save_subtitle( $post_id ) {
// We need to verify this is the 'save_post' we're looking for
// If our nonce is not found, we'll bail.
if ( ! isset( $_POST['wpsnipp_subtitle_metabox_nonce'] ) ) {
return;
}
$nonce = $_POST['wpsnipp_subtitle_metabox_nonce'];
// If the nonce is not valid, we'll bail
if ( ! wp_verify_nonce( $nonce, 'wpsnipp_subtitle_metabox' ) ) {
return;
}
// If this is an autosave, our form has not been submitted, so we'll bail
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
// If the current user doesn't have permission, we'll bail.
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
// OK, its safe for us to save the data now.
// Sanitize user input.
$subtitle = sanitize_text_field( $_POST['wpsnipp-subtitle'] );
// Update the meta field in the database.
update_post_meta( $post_id, 'wpsnipp_post_subtitle', $subtitle );
}
add_action( 'save_post', 'wpsnipp_save_subtitle' );
Recent Comments