How to get my Custom Post Type to display in Recent Posts using “pre_get_posts”

Well, you SHOULDN’T use pre_get_posts, as it will alter ALL the queries in the site.

Also, the query made by the recent posts plugin is not the main query. The main query is made for displaying the current page, after parsing the query variables from URL, and it is responsible, among other things for the current page template.

What you SHOULD do is eighter filter widget_posts_args:

add_filter( 'widget_posts_args', 'wp130512_recent_posts_args');

/**
 * Add CPTs to recent posts widget
 *
 * @param array $args default widget args.
 * @return array $args filtered args.
 */
function wp130512_recent_posts_args($args) {
    $args['post_type'] = array('post', 'my_CPT');
    return $args;
}

OR

extend the recent posts widget class (WP_Widget_Recent_Posts) for more control.

Example code: http://rollinglab.com/2012/06/extend-wordpress-recent-posts-widget/

Leave a Comment