β²οΈ Estimated reading time: 6 min
π Trending Posts Widget for WordPress β Show Popular Posts by Views. Add a powerful βTrending Postsβ widget to your WordPress site using this custom PHP code. Learn how to display your most viewed articles based on post meta values like post_views_count
.
π Display Your Most Popular Posts With a Custom Trending Widget
Displaying trending or most-viewed posts is a smart way to keep your visitors engaged. It encourages exploration, increases page views, and promotes your top-performing content. In this tutorial, weβll show you how to add a custom βTrending Postsβ widget to your WordPress site using a simple PHP code snippet.
This widget will dynamically pull the top posts based on their view count using a custom field (post_views_count
). It also includes support for caching using transient
to ensure fast load times and less server stress.
π§© Step-by-Step: How the Trending Posts Widget Works
β 1. Widget Registration
The widget is registered using register_widget()
inside a widgets_init
hook.
add_action('widgets_init', 'register_trending_posts_widget');
function register_trending_posts_widget() {
register_widget('Trending_Posts_Widget');
}
β 2. Widget Class Structure
The widget is built by extending the WP_Widget
class and defining key functions:
__construct()
β Widget name and description.widget()
β Front-end output of trending posts.form()
β Admin form in Widgets panel.update()
β Save form settings and clear the cache.
π§ PHP Code: Trending Posts Widget
Below is the complete code to add to your themeβs functions.php
or inside a custom plugin:
<?php
/**
* Trending Posts Widget
*/
// Register the widget
function register_trending_posts_widget() {
register_widget('Trending_Posts_Widget');
}
add_action('widgets_init', 'register_trending_posts_widget');
// Define the widget class
class Trending_Posts_Widget extends WP_Widget {
public function __construct() {
parent::__construct(
'trending_posts_widget',
__('Trending Posts', 'text_domain'),
array('description' => __('A widget to display trending posts based on views.', 'text_domain'))
);
}
public function widget($args, $instance) {
echo $args['before_widget'];
$title = !empty($instance['title']) ? $instance['title'] : __('Trending Posts', 'text_domain');
echo $args['before_title'] . apply_filters('widget_title', $title) . $args['after_title'];
$num_posts = !empty($instance['num_posts']) ? absint($instance['num_posts']) : 5;
$cache_key = 'trending_posts_cache_' . $num_posts;
$trending_posts = get_transient($cache_key);
if ($trending_posts === false) {
$trending_query = new WP_Query(array(
'posts_per_page' => $num_posts,
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'ignore_sticky_posts' => true
));
ob_start();
if ($trending_query->have_posts()) {
echo '<ul>';
while ($trending_query->have_posts()) {
$trending_query->the_post();
echo '<li>';
if (has_post_thumbnail()) {
echo '<a href="' . get_permalink() . '">' . get_the_post_thumbnail(get_the_ID(), 'thumbnail', array('class' => 'trending-thumb')) . '</a> ';
}
echo '<a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
}
echo '</ul>';
} else {
echo '<p>' . __('No trending posts found.', 'text_domain') . '</p>';
}
wp_reset_postdata();
$trending_posts = ob_get_clean();
set_transient($cache_key, $trending_posts, HOUR_IN_SECONDS);
}
echo $trending_posts;
echo $args['after_widget'];
}
public function form($instance) {
$title = !empty($instance['title']) ? $instance['title'] : __('Trending Posts', 'text_domain');
$num_posts = !empty($instance['num_posts']) ? absint($instance['num_posts']) : 5;
?>
<p>
<label for="<?php echo esc_attr($this->get_field_id('title')); ?>"><?php _e('Title:', 'text_domain'); ?></label>
<input class="widefat" id="<?php echo esc_attr($this->get_field_id('title')); ?>" name="<?php echo esc_attr($this->get_field_name('title')); ?>" type="text" value="<?php echo esc_attr($title); ?>">
</p>
<p>
<label for="<?php echo esc_attr($this->get_field_id('num_posts')); ?>"><?php _e('Number of Posts:', 'text_domain'); ?></label>
<input class="widefat" id="<?php echo esc_attr($this->get_field_id('num_posts')); ?>" name="<?php echo esc_attr($this->get_field_name('num_posts')); ?>" type="number" min="1" max="20" value="<?php echo esc_attr($num_posts); ?>">
</p>
<?php
}
public function update($new_instance, $old_instance) {
$instance = array();
$instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';
$instance['num_posts'] = (!empty($new_instance['num_posts'])) ? absint($new_instance['num_posts']) : 5;
delete_transient('trending_posts_cache_' . $instance['num_posts']); // clear cache
return $instance;
}
}
?>
π Notes on Usage
- The widget assumes you already have a custom field
post_views_count
updated manually or via a separate plugin. - You can use any plugin like Post Views Counter or your own script to increment this meta key.
- The widget caches results for 1 hour using WordPress
transients
for improved performance. - Works seamlessly with any modern WordPress theme that supports widgets.

π Tips to Improve the Widget
- Add fallback thumbnail image using a conditional
else
inhas_post_thumbnail()
. - Use CSS to customize the output style of
.trending-thumb
. - Allow filtering by category or post type in future enhancements.
- Make it Gutenberg block-ready for block themes.
π§ Final Thoughts
Using this widget, you give your site visitors access to the most engaging content on your blog. Itβs great for blogs, magazines, news sites, or any content-heavy platform that thrives on post visibility.
π For more tutorials like this, consider subscribing to our blog.
π© Do you have questions or suggestions? Leave a comment or contact us!
π·οΈ Tags: WordPress widget, trending posts, post views, custom widget, PHP snippet, WP_Query, WordPress development, cache with transients, post meta, WP_Widget
π’ Hashtags: #WordPress, #TrendingPosts, #WidgetDev, #WPCustomCode, #PHPTutorial, #PostViews, #WPQuery, #Caching, #WPWidgets, #WebDevelopment
π‘ Developer’s Wrap-Up
The “Trending Posts Widget” is a must-have feature for any WordPress site looking to increase user engagement. With just a bit of code, you can create a powerful tool that highlights your site’s best content based on real user behavior. Add it today and watch your page views climb!
Only logged-in users can submit reports.
Discover more from HelpZone
Subscribe to get the latest posts sent to your email.