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

Estimated reading time: 5 min

If you’re looking for a way to display the most popular posts on your WordPress site, adding a Trending Posts Widget to your Wordoress site is a great solution. This widget will dynamically show posts based on their view count, helping visitors find your most engaging content. In this guide, you’ll learn how to create and install a custom WordPress widget for trending posts.


Why Use a Trending Posts Widget?

This widget provides several benefits:

  • Boost Engagement: Showcasing your most viewed posts encourages more clicks.
  • Improves Navigation: Helps users find high-quality content easily.
  • Increases Pageviews: Visitors stay longer by exploring popular articles.

Step 1: Add the Trending Posts Code

To create this widget, add the following code to your theme’s functions.php file or create 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'))
        );
    }

    // Front-end display of widget
    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'];

        // Get number of posts from settings, default is 5
        $num_posts = !empty($instance['num_posts']) ? absint($instance['num_posts']) : 5;

        // Check for cached results
        $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', // Ensure this field is updated correctly
                '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); // Cache for 1 hour
        }

        echo $trending_posts;
        echo $args['after_widget'];
    }

    // Back-end widget form
    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
    }

    // Save widget form values
    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 when updating
        return $instance;
    }
}


Step 2: Activate the Widget

Once you have added the code, follow these steps:

  1. Go to Appearance β†’ Widgets in your WordPress admin panel.
  2. Look for “Trending Posts” in the available widgets.
  3. Drag and drop it into your preferred sidebar or footer.
  4. Set the widget title and number of posts to display.
  5. Save the widget and check your website.

Step 3: Ensure Post Views Are Tracked

This widget relies on the post_views_count meta key to track views. If you don’t already track views, install the WP-PostViews plugin or add this function to functions.php:

function track_post_views($post_id) {
    if (!is_single()) return;
    
    $count = get_post_meta($post_id, 'post_views_count', true);
    $count = empty($count) ? 0 : $count;
    $count++;
    update_post_meta($post_id, 'post_views_count', $count);
}
add_action('wp_head', function() {
    if (is_single()) {
        track_post_views(get_the_ID());
    }
});

Conclusion

Adding a trending posts to your WordPress site is a great way to highlight your most popular content and improve engagement. By following this guide, you can easily integrate this feature into your site. If you have any questions or need customization, feel free to leave a comment below!

πŸš€ Happy Blogging! πŸš€


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