skip to Main Content

WordPress Code Snippets


How to Create a Custom Widget in WordPress for Recent Posts

Add a simple widget to display recent posts.

class Recent_Posts_Widget extends WP_Widget {
    function __construct() {
        parent::__construct('recent_posts_widget', __('Recent Posts', 'text_domain'), array('description' => __('Displays recent posts', 'text_domain')));
    }

    public function widget($args, $instance) {
        $recent_posts = wp_get_recent_posts(array('numberposts' => 5));
        echo $args['before_widget'];
        echo '<ul>';
        foreach ($recent_posts as $post) {
            echo '<li><a href="' . get_permalink($post['ID']) . '">' . esc_html($post['post_title']) . '</a></li>';
        }
        echo '</ul>';
        echo $args['after_widget'];
    }
}

add_action('widgets_init', function() {
    register_widget('Recent_Posts_Widget');
});


I’m a WordPress developer with 10+ years of experience in WooCommerce and custom plugins. I combine technical expertise with design flair to help you create standout, user-friendly websites. Let’s transform your digital presence!

Best WordPress Hosting
Back To Top
Search