Best way to detect if you are in a SINGLE POST page

I’ve tried to sort this out before for my own purposes. As far as I can tell …

  • post_type is not really set anywhere for the post post type.
  • For the page post type I only see the post type key in
    queried_object.
  • For CPT types there is a post_type key in query_vars and also in
    query.
  • Nav menus appear to behave like other CPTs in this respect.

The data is very inconsistent but if you eliminate pages and CPT’s I believe you can assume the post type.

Edit: Working code from @EricHolmes:

add_action( 'pre_get_posts', 'something_for_single_posts_only' ) ; 
function something_for_single_posts_only( $query ) { 
  if( $query->is_main_query() 
    && $query->is_singular() 
    && ! $query->get( 'post_type' ) 
    && ! $query->is_page() 
    && ! $query->is_attachment() 
  ) { 
      // do something for single posts only. 
  } 
} 

We check for is_singular, no post type (CPTs have post_type in query_vars), not a page or attachment.

Leave a Comment