Add a Custom Post Meta Box in WordPress

Add a custom meta box to the post editor for storing additional data without a plugin like ACF. For more on registering custom fields.

add_action( 'add_meta_boxes', function () {
    add_meta_box(
        'savvy_post_subtitle',
        'Post Subtitle',
        'savvy_subtitle_metabox_html',
        'post',
        'normal',
        'high'
    );
} );

function savvy_subtitle_metabox_html( $post ) {
    $value = get_post_meta( $post->ID, '_savvy_subtitle', true );
    wp_nonce_field( 'savvy_subtitle_nonce', 'savvy_subtitle_nonce' );
    printf(
        '<input type="text" name="savvy_subtitle" value="%s" style="width:100%%;" />',
        esc_attr( $value )
    );
}

add_action( 'save_post', function ( $post_id ) {
    if ( ! isset( $_POST['savvy_subtitle_nonce'] ) ||
         ! wp_verify_nonce( $_POST['savvy_subtitle_nonce'], 'savvy_subtitle_nonce' ) ) {
        return;
    }

    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }

    if ( isset( $_POST['savvy_subtitle'] ) ) {
        update_post_meta(
            $post_id,
            '_savvy_subtitle',
            sanitize_text_field( $_POST['savvy_subtitle'] )
        );
    }
} );

Add to functions.php. Change the meta key, label, and input type to match your needs.

Discussion
[  0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!