Increasing post view count automatically

The question:

I am testing a ranking system for posts, and I’d like help with the below:

Upon publishing a new post, I’d like the post view count to immediately have a random number between 829 and 1013 added to it.

Could you please tell me how I can do that? If you offer any code, kindly let me know exactly where to put it.

Thank you.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

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.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment