Upon publishing an unpublished draft, I'd like the custom meta value "post views count" to be set to a random variable between 829
and 1013
.
I am using the code below, which doesn't always work. It works when I create a test draft and publish it immediately, but not when I save a post for a few days or assign it to another writer it doesn't work.
NOTE: I don't want to create a new custom field. I just want to update the existing field, which is called
post_views_count
.
function wpse_custom_field_on_publish( $new, $old, $post ) {
if ( $new == 'publish' && $old != 'publish' && !get_post_meta( $post->ID, 'post_views_count', true ) ) {
update_post_meta( $post->ID, 'post_views_count', rand(829, 1013), true );
}
}
add_action( 'transition_post_status', 'wpse_custom_field_on_publish', 10, 3 );