Last active
October 12, 2017 14:46
-
-
Save kirasiris/4fc10d31e07b362e1c8860b75e1dbe44 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//You can actually wrap the function into Javascript | |
//in order to make the counts valid if an user clicks on a button or title (<h1></h1>;<div></div>) | |
//not just on the refresh of the post/page | |
document.getElementById("readmore").addEventListener("click", function( event ) { | |
// display the current click count inside the clicked div | |
event.target.textContent = "click count: " + event.detail; | |
}, false); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
This php block goes into your functions.php file. | |
Notice that if you're using the WP Super Cache plugin by Auttomatic, it will affect the function. Deactivate it if neccesary. | |
*/ | |
// function to display number of posts. | |
function getPostViews($postID){ | |
$count_key = 'post_views_count'; | |
$count = get_post_meta($postID, $count_key, true); | |
if($count==''){ | |
delete_post_meta($postID, $count_key); | |
add_post_meta($postID, $count_key, '0'); | |
return "0 Views"; | |
} | |
return $count.' Views'; | |
} | |
// function to count views. | |
function setPostViews($postID) { | |
$count_key = 'post_views_count'; | |
$count = get_post_meta($postID, $count_key, true); | |
if($count==''){ | |
$count = 0; | |
delete_post_meta($postID, $count_key); | |
add_post_meta($postID, $count_key, '0'); | |
}else{ | |
$count++; | |
update_post_meta($postID, $count_key, $count); | |
} | |
} | |
// Add it to a column in WP-Admin | |
add_filter('manage_posts_columns', 'posts_column_views'); | |
add_action('manage_posts_custom_column', 'posts_custom_column_views',5,2); | |
function posts_column_views($defaults){ | |
$defaults['post_views'] = __('Views'); | |
return $defaults; | |
} | |
function posts_custom_column_views($column_name, $id){ | |
if($column_name === 'post_views'){ | |
echo getPostViews(get_the_ID()); | |
} | |
} | |
?> | |
<?php | |
// You have to call the function using this echo if you want to put it in the index,archive, or search file. It needs to be put inside the loop | |
echo getPostViews(get_the_ID()); | |
?> | |
<?php | |
// This one goes in the single,page files. If you do not put it will trow an error, and/or the function may not work properly. It needs to go inside the loop | |
setPostViews(get_the_ID()); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment