1. Please write below code in functions.php
<?php
// function to display number of views for post
function wp_get_post_views($postId){
$count_key = 'count_post_views';
$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 set post views
function wp_set_post_views($postId) {
$count_key = 'count_post_views';
$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 views column to wp_admin
add_filter('manage_posts_columns', 'wp_posts_views_column');
function wp_posts_views_column($defaults){
$defaults['post_views'] = __('Views');
return $defaults;
}
add_action('manage_posts_custom_column', 'wp_posts_views_custom_column',10,2);
function wp_posts_views_custom_column($column_name, $id){
if($column_name === 'post_views'){
echo wp_get_post_views(get_the_ID());
}
}
?>
<?php
// function to display number of views for post
function wp_get_post_views($postId){
$count_key = 'count_post_views';
$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 set post views
function wp_set_post_views($postId) {
$count_key = 'count_post_views';
$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 views column to wp_admin
add_filter('manage_posts_columns', 'wp_posts_views_column');
function wp_posts_views_column($defaults){
$defaults['post_views'] = __('Views');
return $defaults;
}
add_action('manage_posts_custom_column', 'wp_posts_views_custom_column',10,2);
function wp_posts_views_custom_column($column_name, $id){
if($column_name === 'post_views'){
echo wp_get_post_views(get_the_ID());
}
}
?>
2. Now, open singe.php and add below code inside the loop.
<?php
wp_set_post_views(get_the_ID());
?>
3. Please write below code for display views of post.
<?php
wp_get_post_views(get_the_ID());
?>
4. If you want to sort post by view than add below code:
<?php
$args = array( 'numberposts' => 10,
'orderby' => 'meta_value',
'meta_key' => 'count_post_views',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish'
);
$mostViewedPosts = get_posts( $args );
foreach( $mostViewedPosts as $mostViewedPost ) {
/* Write your code here */
}
?>
No comments:
Post a Comment