When working with WordPress post meta data, we may want to create our own custom post meta fields. To create WordPress post meta fields when a post is created, we can do so with a PHP function like this:
function set_custom_post_meta_on_insert_post( $post_id, $post, $update ) {
// If this is a revision, is not of type 'post', or is an update, don't create the post meta
if ( wp_is_post_revision( $post_id ) || 'post' !== $post->post_type || $update ) {
return;
}
update_post_meta( $post_id, 'my_custom_post_meta', 'my initial value' );
}
We can then attach our function to the 'wp_insert_post'
action hook:
add_action( 'wp_insert_post', 'set_custom_post_meta_on_insert_post', 10, 3 );
So our complete code looks like this:
function set_custom_post_meta_on_insert_post( $post_id, $post, $update ) {
// If this is a revision, is not of type 'post', or is an update, don't create the post meta
if ( wp_is_post_revision( $post_id ) || 'post' !== $post->post_type || $update ) {
return;
}
update_post_meta( $post_id, 'my_custom_post_meta', 'my initial value' );
}
add_action( 'wp_insert_post', 'set_custom_post_meta_on_insert_post', 10, 3 );
A note on the above code: the function above assumes we only want to create a custom post meta on posts of type ‘post’. We can adjust this logic for any post type by modifying or extending the conditional check 'post' !== $post->post_type
to include any post type we desire. For example, if we have a custom post type 'movie_review'
, we could change our function to:
function set_custom_post_meta_on_insert_post( $post_id, $post, $update ) {
// If this is a revision, is not of type 'movie_review', or is an update, don't create the post meta
if ( wp_is_post_revision( $post_id ) || 'movie_review' !== $post->post_type || $update ) {
return;
}
update_post_meta( $post_id, 'my_custom_post_meta', 'my initial value' );
}
add_action( 'wp_insert_post', 'set_custom_post_meta_on_insert_post', 10, 3 );
More info on the WordPress hooks and functions used above: