This WordPress custom code automatically sets a random initial post view count for new posts using the Post Views Counter plugin. It ensures that every newly created post starts with a random number of views between 512 and 768 to simulate some activity before the post is officially live.
- Hooks into the
save_postaction to trigger the function when a new post is saved. - Applies only to posts that are new (in
auto-draftordraftstatus) and does not modify existing posts. - Sets a random number of views between 512 and 768 on each new post using the Post Views Counter plugin's
pvc_update_post_viewsfunction.
Paste the code for the custom post views function inside your theme's functions.php file.
/**
* ANDORU CUSTOM VIEW: Set random initial post views for new posts
*/
function set_initial_random_post_views_on_new_post($post_id, $post) {
// Skip if this is an auto-save or a revision
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
// Skip if it's an edit or a non-new post
if ($post->post_status !== 'auto-draft' && $post->post_status !== 'draft') {
return;
}
// Only apply to posts
if ($post->post_type !== 'post') {
return;
}
// Generate random views between 512 and 768
$random_views = rand(512, 768);
// Set the random views using the Post Views Counter function
pvc_update_post_views($post_id, $random_views);
}
// Hook into 'save_post' action
add_action('save_post', 'set_initial_random_post_views_on_new_post', 10, 2);- WordPress Version: Ensure you are using WordPress and have administrative access to your site.
- Post Views Counter Plugin: Install and activate the Post Views Counter plugin by dFactory.
-
Log in to WordPress Admin:
- Go to your WordPress dashboard by logging in with an administrator account.
-
Navigate to Your Theme's
functions.php:- In the WordPress dashboard, go to Appearance > Theme File Editor.
- In the right sidebar, find and click on the
functions.phpfile under your active theme.
-
Add the Custom Code:
- Scroll down to the bottom of the
functions.phpfile and paste the code from the Code section.
- Scroll down to the bottom of the
-
Save the Changes:
- Once you’ve added the code, click the Update File button to save your changes.
-
Test the Functionality:
- Create a new post from the WordPress dashboard. After saving the post, it should automatically have a random number of views between 512 and 768.
- You can check the post views by viewing the post and checking the post views counter (depending on how the Post Views Counter plugin is set up to display).
- If you want to display post views on your site, ensure that the Post Views Counter plugin is properly configured to show the views for each post.
- You can adjust the random range by changing the numbers in the
rand()function, e.g.,rand(512, 1920).
This solution helps give the appearance of early engagement on newly published content, ideal for blogs and websites looking to simulate initial activity.