Count Post and Page Views based on meta_value Using Shortcode in Dashboard Widget
I'm working on a counter that, each time a post is viewed, the meta value is updated by 1. This works fine, but I cannot seem to figure out how to make it count posts and pages, including the home page (is_front_page
).
This is the code:
function counter_posts( $post_id ) {
if ( is_user_logged_in() current_user_can( 'administrator' ) ) return;
$count_key = 'count_views';
$count = get_post_meta( $post_id, $count_key, true );
if ( $count == '' ) {
$count = 0;
delete_post_meta( $post_id, $count_key );
add_post_meta( $post_id, $count_key, '1' );
} else {
$count++;
update_post_meta($post_id, $count_key, $count);
}
}
add_action( 'wp_head', 'track_posts' );
function track_posts( $post_id ) {
// I don't know how to incorporate the counter for all post and pages, not just single posts
// not using the line below does not work
// if ( ! is_single() ) return;
if ( empty( $post_id ) ) {
global $post;
$post_id = $post-ID;
}
counter_posts($post_id);
}
add_shortcode( 'count_functions', 'display_counter' );
function display_counter( $atts ) {
extract( shortcode_atts( array(
'num' = 10,
'cat' = '',
), $atts ) );
$temps = explode( ',', $cat );
$array = array();
foreach ( $temps as $temp ) $array[] = trim( $temp );
$cats = ! empty( $cat ) ? $array : '';
?
ol
?php $popular = new WP_Query( array( 'posts_per_page' = $num, 'meta_key' = 'count_views', 'orderby' = 'meta_value_num', 'order' = 'DESC', 'category__in' = $cats ) );
while ( $popular-have_posts() ) : $popular-the_post(); ?
lia href=?php the_permalink(); ??php the_title(); ?/a
?php $total_views = get_post_meta( get_the_ID(), 'count_views',true );
if ( $total_views == '' || $total_views == 0) {
echo (no views yet);
}
elseif ( $total_views == 1 ) {
echo (viewed once);
} else {
echo (viewed $total_views times); } ?/li
?php endwhile; wp_reset_postdata(); ?
/ol
?php
}
add_action( 'wp_dashboard_setup', 'count_dashboard_widget' );
function count_dashboard_widget() {
global $wp_meta_boxes;
wp_add_dashboard_widget( 'count_views_widget', 'Most Read', 'count_functions_widget'); }
function count_functions_widget() {
echo 'br';
echo do_shortcode('[count_views]');
echo 'br';
}
I tried editing this if ( ! is_single() ) return;
into this if ( is_single() || is_singular('page') ) return;
, but that did not work. I also tried to remove it, which did not work either.
Any suggestions please?
Topic meta-value post-meta count Wordpress
Category Web