How to Use the πŸ“Œ Trending Posts Widget Code in WordPress

⏲️ 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 in has_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!

Report an issue (max 5 words):

Only logged-in users can submit reports.


Discover more from HelpZone

Subscribe to get the latest posts sent to your email.

Want to support us? Let friends in on the secret and share your favorite post!

Photo of author

Flo

How to Use the πŸ“Œ Trending Posts Widget Code in WordPress

Published

Update

Welcome to HelpZone.blog, your go-to hub for expert insights, practical tips, and in-depth guides across technology, lifestyle, business, entertainment, and more! Our team of passionate writers and industry experts is dedicated to bringing you the latest trends, how-to tutorials, and valuable advice to enhance your daily life. Whether you're exploring WordPress tricks, gaming insights, travel hacks, or investment strategies, HelpZone is here to empower you with knowledge. Stay informed, stay inspired because learning never stops! πŸš€

πŸ‘ Like us on Facebook!

Closing in 10 seconds

Leave a Reply