Increasing post view count automatically

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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 stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x