Function post view count berikut ini akan menampilkan berapa banyak postingan kamu dilihat oleh pengunjung blog. Cara membuatnya gampang dan tanpa plugin, hanya menambahkan beberapa baris kode di file theme functions.php
di theme WordPress kamu. Berikut ini strategi bagi merancang konter post view di blog WordPress.
Contoh di idnetter.com:
Langkah Pertama-tama – Merancang Function
Sahabat dapat mengedit file functions.php
lewat file editor di Dashboard admin: Appereance
> Editor
> pilih functions.php
, tambahkan baris kode berikut:
// Bagi menjaga hitungan akurat
remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
function id_set_post_views($postID) {
$count_key = 'id_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);
}
}
function id_track_post_views ($post_id) {
if ( !is_single() ) return;
if ( empty ( $post_id) ) {
global $post;
$post_id = $post->ID;
}
id_set_post_views($post_id);
}
add_action( 'wp_head', 'id_track_post_views');
function id_get_post_views($postID){
$count_key = 'id_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;
}
return $count;
}
Setelah selesai klik Update File, langkah berikutnya tinggal bagaimana cara menampilkan konter post view dengan function yang telah kita bikin seperti diatas, ikuti langkah kedua berikut ini.
Langkah Kedua – Menampilkan Konter
Bagi menampilkan konter post view, tambahkan kode berikut ke file single.hp
<span class=post-view-counter>
Artikel ini telah dilihat : <?php echo id_get_post_views(get_the_ID()); ?> kali.
</span>
Sahabat pun dapat menampilkan konter post view di halaman utama blog kamu dengan kode seperti diatas. Gampang bukan? kini kamu dapat mengetahui berapa banyak orang yang melihat postingan diwebsite kamu.
Selamat mencoba.
Referensi : WPBeginer
Sumber https://idnetter.com