How To Add A Custom Meta Box And Save Custom Fields In WordPress
A meta box is an extra panel in the post editor where you can add custom fields, like a subtitle, a price or a link. This example creates a text field, saves it securely and displays it on the front end.
Step 1: register the meta box
function lotgrafix_add_meta_box() {
add_meta_box(
'lotgrafix_subtitle_box',
__( 'Subtitle', 'lotgrafix' ),
'lotgrafix_meta_box_html',
'post',
'normal',
'high'
);
}
add_action( 'add_meta_boxes', 'lotgrafix_add_meta_box' );
Change 'post' to a page or to a custom post type name to show the box there.
Step 2: print the field
function lotgrafix_meta_box_html( $post ) {
wp_nonce_field( 'lotgrafix_save_subtitle', 'lotgrafix_subtitle_nonce' );
$value = get_post_meta( $post->ID, '_lotgrafix_subtitle', true );
echo '<input type="text" name="lotgrafix_subtitle" value="' . esc_attr( $value ) . '" style="width:100%">';
}
Step 3: save the value
function lotgrafix_save_subtitle( $post_id ) {
if ( ! isset( $_POST['lotgrafix_subtitle_nonce'] ) ) {
return;
}
if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['lotgrafix_subtitle_nonce'] ) ), 'lotgrafix_save_subtitle' ) ) {
return;
}
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
if ( isset( $_POST['lotgrafix_subtitle'] ) ) {
update_post_meta(
$post_id,
'_lotgrafix_subtitle',
sanitize_text_field( wp_unslash( $_POST['lotgrafix_subtitle'] ) )
);
}
}
add_action( 'save_post', 'lotgrafix_save_subtitle' );
Step 4: show it in your template
$lotgrafix_subtitle = get_post_meta( get_the_ID(), '_lotgrafix_subtitle', true );
if ( $lotgrafix_subtitle ) {
echo '<p class="lotgrafix-subtitle">' . esc_html( $lotgrafix_subtitle ) . '</p>';
}
Security checklist
- A nonce confirms the request came from your form.
- Ignore autosaves, or the field can be erased.
- Check user permissions with
current_user_can(). - Sanitize on save and escape on output.
- A meta key that starts with an underscore is hidden from the default Custom Fields box.


