Skip to content

Instantly share code, notes, and snippets.

@mralaminahamed
Created December 21, 2025 06:04
Show Gist options
  • Select an option

  • Save mralaminahamed/c56dda3cb319c45a546b467831e26008 to your computer and use it in GitHub Desktop.

Select an option

Save mralaminahamed/c56dda3cb319c45a546b467831e26008 to your computer and use it in GitHub Desktop.
<?php
// Function to track and set post views
function set_post_views($post_id) {
if (!is_single()) return; // Only track on single post views
$count_key = 'post_views_count';
$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, '0');
} else {
$count++;
update_post_meta($post_id, $count_key, $count);
}
}
add_action('wp_head', 'set_post_views'); // Call it on every page load (checks if single)
// Optional: Function to get views (for display)
function get_post_views($post_id) {
$count_key = 'post_views_count';
$count = get_post_meta($post_id, $count_key, true);
if ($count == '') {
return "0 Views";
}
return $count . ' Views';
}
// Shortcode to display popular posts: [popular_posts number="5" show_views="yes"]
function popular_posts_shortcode($atts) {
$atts = shortcode_atts(array(
'number' => 5, // Number of posts to show
'show_views' => 'yes', // Show view count? yes/no
'title' => 'Popular Posts', // Title above the list
), $atts, 'popular_posts');
$query = new WP_Query(array(
'posts_per_page' => $atts['number'],
'post_type' => 'post',
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'ignore_sticky_posts' => true,
));
if (!$query->have_posts()) {
return '<p>No popular posts found yet.</p>';
}
$output = '<div class="popular-posts">';
if (!empty($atts['title'])) {
$output .= '<h3>' . esc_html($atts['title']) . '</h3>';
}
$output .= '<ul>';
while ($query->have_posts()) {
$query->the_post();
$output .= '<li>';
$output .= '<a href="' . get_permalink() . '">' . get_the_title() . '</a>';
if ($atts['show_views'] === 'yes') {
$output .= ' <span>(' . get_post_views(get_the_ID()) . ')</span>';
}
$output .= '</li>';
}
$output .= '</ul></div>';
wp_reset_postdata();
return $output;
}
add_shortcode('popular_posts', 'popular_posts_shortcode');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment