WordPress

Add and automatically populate post_year metabox

# ------------------------------------------
# ADD AND POPULATE POST YEAR METABOX
# ------------------------------------------
function add_post_year_meta_field() {
    add_meta_box(
        'post_year_meta_box',
        'Post Year',
        'post_year_meta_box_callback',
        'post',
        'side',
        'default'
    );
}
add_action( 'add_meta_boxes', 'add_post_year_meta_field' );

function post_year_meta_box_callback( $post ) {
    $post_year = get_post_meta( $post->ID, 'post_year', true );
    echo '<label for="post_year">Post Year: </label>';
    echo '<input type="text" id="post_year" name="post_year" value="' . esc_attr( $post_year ) . '" size="25" />';
}

function save_post_year_meta_field( $post_id ) {
    if ( array_key_exists( 'post_year', $_POST ) ) {
        update_post_meta(
            $post_id,
            'post_year',
            sanitize_text_field( $_POST['post_year'] )
        );
    }
}
add_action( 'save_post', 'save_post_year_meta_field' );

function update_post_year_on_save( $post_id ) {
    if ( get_post_type( $post_id ) === 'post' ) {
        $post_year = get_the_date( 'Y', $post_id );
        update_post_meta( $post_id, 'post_year', $post_year );
    }
}
add_action( 'save_post', 'update_post_year_on_save' );

This function will add a custom meta box to the post edit screen with a text field for the “post_year” meta field. The value of the field will be automatically updated with the post’s year whenever the post is saved.