< Back to Code

PHP – Create shortcode to count post view in wordpress

Step 1:

Create PODS custom field for your POST / PAGE

Create a NUMBER field

Name it page_view (no capitalize)

 

Step 2:

Find your functions.php file in your theme > wp-content \ themes \ your-theme \functions.php

Step 3:

use the PHP as below

function create_view_counter(){

/*page_view will be the name of field created in PODS*/
$view = get_post_meta(get_the_ID(), 'page_view', true);


/* check if your field is empty */
if ($view == ''){
$view = 0;
}

/*auto add 1 view to your counter */

$view = $view+1;


/*update your counter back to WP database */
update_post_meta(get_the_ID(), 'page_view', $view);


/*display the counter in your page */
return "View: $view";

}
//create the shortcode by the function above
add_shortcode ('viewcounter', 'create_view_counter');

Step 4:

Put the shortcode in your post content (if you don’t  put it won’t count) so better to put it where you want it to count. For example theme, or footer…

[viewcounter]

 

en_US

© Copyright by JAYbranding – All rights reserved.