Add Bootstrap Classes to Recent Posts Widget

Unfortunately, this isn’t quite as easy as you might expect, nor is it properly achievable by using filters. WordPress offers very little hooks for widgets in general, let alone for widget content. However, as all widgets are generated by classes, you can extend the functionality WordPress offers by creating your own widget, extending the recent posts widget.

For basic information on widgets and how to register them, have a look at the Codex.

As for the implementation in this specific case, you would have to start out by creating a class extending the recent posts widget class (WP_Widget_Recent_Posts):

class MyPlugin_Widget_Recent_Posts_Bootstrap extends WP_Widget_Recent_Posts {

}

As you want the widget to be the same as the normal recent posts widget, you don’t have to do anything to the update and form methods, which are the methods used for displaying the widget settings form and updating the widget accordingly. Thus, you don’t have to implement these methods in your class, and just inherit them from WP_Widget_Recent_Posts.

The two methods you do have to implement are the constructor (__construct) and the widget display method (widget). In the constructor, you simply set up the widget settings as described in the codex:

class MyPlugin_Widget_Recent_Posts extends WP_Widget_Recent_Posts {

    public function __construct() {
        WP_Widget::__construct(
            'myplugin-recent-posts',
            __( 'My Plugin: Recent Posts', 'myplugin' ),
            array(
                'classname' => 'myplugin_widget_recent_posts',
                'description' => __( 'My recent posts widget', 'myplugin' )
            )
        );
    }

}

Next, you have to implement the display method, widget. Now, even though this sounds like (and is) a very “ugly” solution, it’s your best bet: you should copy the content of the display method from WP_Widget_Recent_Posts and change it to fit your needs. Besides the class names you want to add, the only change that I would advise you to make is changing the cache key from widget_recent_posts to something like myplugin_widget_recent_posts.

This requires some coding on your side, but unfortunately, it’s the best solution there currently is.