Updating post_views_count on publish [duplicate]

So this is the code I earlier posted.

// Create custom field on post publish
function wpse_custom_field_on_publish( $new, $old, $post ) {

  if ( $new == 'publish' && $old != 'publish' && !get_post_meta( $post->ID, 'post_views_count', true ) ) {
    add_post_meta( $post->ID, 'post_views', rand(829, 1013), true );
  }

}
add_action( 'transition_post_status', 'wpse_custom_field_on_publish', 10, 3 );

Let me explain what this code actually does. When you publish or schedule a post, upon publishing this function checks for a custom field named post_views_count in your post. If it does not exist then it will create a post_views_count custom field and add a random value between 829 and 1013.

I think you had some issue with this code failing some times, so you changed add_post_meta with update_post_meta which will also fail sometimes because if a post does not already have post_views_count meta field then it will skip and do noting.

So what you needed to do instead is to add different tasks for each cases, what to do if this field already exists, else what should it do if it does not.

// Create custom field on post publish
function wpse_custom_field_on_publish( $new, $old, $post ) {

  if ( ( $new == 'publish' || $new == 'pending' ) && $old != 'publish' ) {

      if ( !get_post_meta( $post->ID, 'post_views_count', true ) ) {
          add_post_meta( $post->ID, 'post_views_count', rand(829, 1013), true );
      } else {
          update_post_meta( $post->ID, 'post_views_count', rand(829, 1013) );
      }

  }

}
add_action( 'transition_post_status', 'wpse_custom_field_on_publish', 10, 3 );

The idea is still same here. But we added additional task for existing fields.

Now there is some limitation with action transition_post_status that it only checks for changes in post status. If you keep changing post status every day/week/etc then this function will also keep changing post_views_count value.

To prevent this function from doing that you can create another meta/custom field and set it’s value to 1 if post is published atleast once in past. And check for this new field value before executing above code.

I will check other answer too, see if it’s a better solution.