Skip to content

Instantly share code, notes, and snippets.

@sabotawsh
Forked from vishalbasnet23/functions.php
Created May 1, 2019 16:59
Show Gist options
  • Save sabotawsh/a9f1121aa23276529bc2a577cf268021 to your computer and use it in GitHub Desktop.
Save sabotawsh/a9f1121aa23276529bc2a577cf268021 to your computer and use it in GitHub Desktop.
Simple Post View Counter WordPress
<?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 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