Membuat jumlah terbaca (post views) di wordpress tanpa plugin

16 November 2014 sashindo

Ada banyak plugin wordpress yang menyediakan fungsi untuk menampilkan jumlah artikel yang sudah terbaca (post-views), akan tetapi untuk dengan fungsi berikut kita bisa lebih menghemat plugins yang terinstall di website kita. Fungsi ini berfungsi untuk mengetahui seberapa banyak artikel di wordpress telah dibaca oleh pengunjung, masukan code berikut di file [symple_highlight color=”blue”]functions.php[/symple_highlight]

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 View";
}
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());
}
};

Lalu masukan code berikut di file [symple_highlight color=”blue”]single.php[/symple_highlight]

<?php setPostViews(get_the_ID()); ?>

Dan terakhir, masukan code berikut ke dalam baris di file [symple_highlight color=”blue”]single.php[/symple_highlight] di mana kita akan memunculkan jumlah post-views (jumlah terbaca):

<?php echo getPostViews(get_the_ID()); ?>

Selamat mencoba…