Display Popular Posts Widget

Create a widget to display the most popular posts based on comment count.

<?php
class Popular_Posts_Widget extends WP_Widget {

    function __construct() {
        parent::__construct(
            'popular_posts_widget',
            __('Popular Posts Widget', 'text_domain'),
            array('description' => __('Displays popular posts based on comment count.', 'text_domain'))
        );
    }

    public function widget($args, $instance) {
        $title = !empty($instance['title']) ? $instance['title'] : __('Popular Posts', 'text_domain');
        $number_of_posts = !empty($instance['number_of_posts']) ? intval($instance['number_of_posts']) : 5;

        $query_args = array(
            'posts_per_page' => $number_of_posts,
            'orderby'        => 'comment_count',
            'order'          => 'DESC',
            'post_status'    => 'publish',
        );

        $popular_posts = new WP_Query($query_args);

        echo $args['before_widget'];
        if (!empty($title)) {
            echo $args['before_title'] . $title . $args['after_title'];
        }
        if ($popular_posts->have_posts()) {
            echo '<ul>';
            while ($popular_posts->have_posts()) {
                $popular_posts->the_post();
                echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
            }
            echo '</ul>';
            wp_reset_postdata();
        }
        echo $args['after_widget'];
    }

    public function form($instance) {
        $title = !empty($instance['title']) ? $instance['title'] : __('Popular Posts', 'text_domain');
        $number_of_posts = !empty($instance['number_of_posts']) ? intval($instance['number_of_posts']) : 5;
        ?>
        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label>
            <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>">
        </p>
        <p>
            <label for="<?php echo $this->get_field_id('number_of_posts'); ?>"><?php _e('Number of posts:'); ?></label>
            <input class="widefat" id="<?php echo $this->get_field_id('number_of_posts'); ?>" name="<?php echo $this->get_field_name('number_of_posts'); ?>" type="number" value="<?php echo esc_attr($number_of_posts); ?>" min="1">
        </p>
        <?php
    }

    public function update($new_instance, $old_instance) {
        $instance = array();
        $instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';
        $instance['number_of_posts'] = (!empty($new_instance['number_of_posts'])) ? intval($new_instance['number_of_posts']) : 5;
        return $instance;
    }
}

function register_popular_posts_widget() {
    register_widget('Popular_Posts_Widget');
}
add_action('widgets_init', 'register_popular_posts_widget');

Post Comment