Increasing post view count automatically [duplicate]

You can automatically add a custom field to each new post on publish (on change status to publish). And then set it’s value to a random number between 829 and 1013.

Here is the function that will do just that.

// 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', true ) ) {
    add_post_meta( $post->ID, 'post_views', rand(829, 1013), true );
  }

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

In above code, post_views is the name of the custom field that we are using to count post views. You should change it to yours before using it in your theme.

Just FYI, this will go in functions.php file.

Leave a Comment