Display Custom Post Types in Recent Posts Widget

How to Display Custom Post Types in Recent Posts Widget

in Widgets
Google+ LinkedIn

WordPress comes with a number of default widgets which allow blog owners to easily add some basic features to their website and one of them is Recent Posts widget. This particular widget, as the name suggests, displays a number of most recent blog posts in WordPress widgetized sidebar. It’s very easy to use, simply drag it to the sidebar and specify number of posts you want to display. But if you have used recent posts widget in past then you might have noticed that any CPT posts you add are not listed in this widget because it does not allow custom post types (CPT). So in this article I will show you how to include custom post types in native recent posts widget. We have also posted about how to add custom post types to RSS feeds and search results.

To add custom post types to the recent posts widget, WordPress has a filter that we can use to modify the WordPress query and specify additional parameters to include required CPT. To display CPT posts, we will be using the post_type parameter and specifying the types of posts that we want to be queried in the recent posts widget.

This PHP code once added to your functions file enables you to include one or more custom post type posts in the native recent posts widget.

// display custom post types 'photos' in recent posts widget
function wcs_cpt_recent_posts_widget( $params ) {
    $params['post_type'] = array( 'photos' );
    return $params;
}
add_filter( 'widget_posts_args', 'wcs_cpt_recent_posts_widget' );

As you can see from the code above, we have included ‘photos’ CPT in this widget, you can replace this with the name of yours. For displaying more than one CPT in recent posts widget, add CPT names in array separated by commas. Here is an example.

// display custom post types 'photos', 'videos' and 'notes' in recent posts widget
function wcs_cpt_recent_posts_widget( $params ) {
    $params['post_type'] = array( 'photos', 'videos', 'notes' );
    return $params;
}
add_filter( 'widget_posts_args', 'wcs_cpt_recent_posts_widget' );

Share the love

If you like this snippet, share it with others!

One Reply on "Display Custom Post Types in Recent Posts Widget"

  1. Roberto Tombola

    This is the best solution I found about it. Thanks
    What about categories, tags, archives?
    I’m trying to extend custom post type taxonomy to all wordpress default widgets.
    They appears already in categories and tags cloud but if I select one the result is a “nothing found”, same if I select Archives.
    Thanks again

Leave a Reply

Your email address will not be published. Required fields are marked *