Mở file functions.php và nhúng đoạn code bên dưới
//Nhúng code này vào file functions.php theme đang dùng require 'wpshare247-posts-view-counter.php';
Tạo file wpshare247-posts-view-counter.php với nội dung như sau:
<?php
///----------------------
add_action( 'wp_head', 'wpshare247_posts_view_counter' );
function wpshare247_posts_view_counter(){
if( is_singular()){
$post_id = get_the_ID();
$wpshare247_post_view = (int)get_post_meta( $post_id, 'wpshare247_post_view', true );
$wpshare247_post_view++;
update_post_meta( $post_id, 'wpshare247_post_view', $wpshare247_post_view );
}
}
//-------------------
add_filter( 'manage_page_posts_columns', 'wpshare247_add_column_view' );
add_filter( 'manage_posts_columns', 'wpshare247_add_column_view' );
function wpshare247_add_column_view( $columns ){
$columns['wpshare247_post_view'] = __('Views', 'wpshare247');
return $columns;
}
add_action('manage_page_posts_custom_column', 'wpshare247_add_column_view_val', 10, 2);
add_action('manage_posts_custom_column', 'wpshare247_add_column_view_val', 10, 2);
function wpshare247_add_column_view_val($key, $post_id){
switch ($key) {
case 'wpshare247_post_view':
$wpshare247_post_view = (int)get_post_meta( $post_id, 'wpshare247_post_view', true );
echo $wpshare247_post_view;
break;
default:
// code...
break;
}
}