Add view count in wordpress posts in post meta.
Put this code in functions.php file
function customSetPostViews() { // Check if we're on a single post page if (!is_single()) { return; // Exit if not a single post } // Get the current post ID $postID = get_the_ID(); // Check if the current user is an admin if (current_user_can('administrator')) { return; // Skip counting for admin } $countKey = 'post_views_count'; $cookieKey = 'post_viewed_' . $postID; // Check if the user has already viewed the post today if (isset($_COOKIE[$cookieKey])) { return; // User has already viewed the post today } // Get the current view count $count = get_post_meta($postID, $countKey, true); if ($count == '') { $count = 0; } // Increment the view count $count++; update_post_meta($postID, $countKey, $count); // Set a cookie to track the user's view setcookie($cookieKey, '1', time() + (12 * 60 * 60), '/'); // Expires in 12 hours } // Hook the function to the 'wp' action to count views when a post is loaded add_action('wp', 'customSetPostViews');
Optional code for show view count in post table.
// Add the view count column to the posts list table function add_view_count_column($columns) { $columns['view_count'] = 'View Count'; return $columns; } add_filter('manage_posts_columns', 'add_view_count_column'); // Display the view count in the custom column function display_view_count_column($column_name, $post_id) { if ($column_name === 'view_count') { $count = get_post_meta($post_id, 'post_views_count', true); echo esc_html($count ? $count : 0); } } add_action('manage_posts_custom_column', 'display_view_count_column', 10, 2); // Hide the view count column by default function hide_view_count_column_by_default($hidden, $screen) { if ($screen->id === 'edit-post') { $hidden[] = 'view_count'; } return $hidden; } add_filter('default_hidden_columns', 'hide_view_count_column_by_default', 10, 2);
Now show post by post view
Put this code in shortcode or where you want show
$args = array( 'post_type' => 'post', // Change to your post type if needed 'meta_key' => 'post_views_count', // Meta key for view count 'orderby' => 'meta_value_num', // Order by numeric meta value 'order' => 'DESC', // Most viewed first 'posts_per_page' => 10, // Number of posts to display ); $query = new WP_Query($args); if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); // Display post title, excerpt, etc. the_title(); the_excerpt(); } wp_reset_postdata(); // Reset post data } else { echo 'No posts found.'; }
0 Comments