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

  1. I created a Custom Post Type (call it “my-post-type”).
  2. I created an archive-my-post-type.php page for displaying all the Custom Post Types.
  3. Looking at the “Recent Posts” section of the Sidebar, I noticed none of custom post types are showing up.
  4. I’d like the Custom Post Types to show in Recent Posts as well.
  5. I read this article here on WP Stack which says I can use pre_get_posts to add my Custom Post Type to the Recent Posts (sidebar).
  6. Tried it. That did not work.

So…

I did some investigation on pre_get_posts and from what I can tell…

  • pre_get_posts is used to alter the main loop.

Also the codex gives this warning:

Identifying Target Queries

When using pre_get_posts, be aware of the query you are changing. One
useful tool is is_main_query(), which can help you ensure that the
query you are modifying is only the main query.

  • That phrase “target queries” in the title seems (to me) to imply that I can “target” which query I want to modify.
  • Also the code from stack also does not use is_main_query().
  • So now I’m wondering… are “Recent Posts” NOT part of the “main query”?

So I added some code to see exactly what queries were run on the page and saw two queries

This query was above the entire page (followed by all my Custom Posts)…

'SELECT SQL_CALC_FOUND_ROWS  wp_posts.* FROM wp_posts  WHERE 1=1  AND wp_posts.post_type="press-release" AND (wp_posts.post_status="publish")  ORDER BY wp_posts.post_date DESC LIMIT 0, 10'

The other query was above the sidebar

'SELECT   wp_posts.* FROM wp_posts  WHERE 1=1  AND wp_posts.post_type="post" AND (wp_posts.post_status="publish")  ORDER BY wp_posts.post_date DESC LIMIT 0, 5'

I’d like to add my Custom Post Type to this query.

CAN (and SHOULD) I accomplish this using pre_get_posts?

I’m pretty green, so I really hope this question makes sense.

1 Answer
1

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