Created
July 7, 2016 16:17
-
-
Save alokstha1/2e3bcab28e86ff652f59a7bac7f10de2 to your computer and use it in GitHub Desktop.
Simple Post View Counter WordPress
This file contains hidden or 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 | |
/** | |
* Post view Count | |
*/ | |
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0); | |
function wpb_set_post_views($postID) { | |
$count_key = 'wpb_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); | |
} | |
} | |
/** | |
* Adding Custom Columns in mangage post table | |
*/ | |
add_filter('manage_post_posts_columns', 'post_column_table_head'); | |
function post_column_table_head( $defaults ) { | |
$defaults['wpb_post_views_count'] = 'Post Views'; | |
return $defaults; | |
} | |
/** | |
* Getting count | |
*/ | |
add_action( 'manage_post_posts_custom_column', 'post_table_content', 10, 2 ); | |
function post_table_content( $column_name, $post_id ) { | |
if ($column_name == 'wpb_post_views_count') { | |
echo get_post_meta( $post_id, 'wpb_post_views_count', true ); | |
} | |
} |
This file contains hidden or 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
<!-- THIS MONTH POPULAR POSTS ---> | |
<ul> | |
<?php | |
$month_popular_args = array( | |
'post_type' => 'post', | |
'posts_per_page' => 10, | |
'meta_key' => 'wpb_post_views_count', | |
'orderby' => 'meta_value_num', | |
'order' => 'DESC', | |
'date_query' => array( | |
array( | |
'year' => $today['year'], | |
'month' => $today['mon'], | |
) | |
) | |
) ; | |
$month_popular_query = new WP_Query( $month_popular_args ); | |
while( $month_popular_query->have_posts() ) : $month_popular_query->the_post(); | |
?> | |
<li> | |
<?php echo the_title(); ?> | |
</li> | |
<?php endwhile; wp_reset_query();?> | |
</ul> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment