How to Hide Single Posts of a Custom Post Type in WordPress

It’s a pretty common situation in WordPress where you’re using a custom post type for, say, a feed on a page, but you don’t want individual posts of that post type visible as separate pages.

One example of this is a staff page. For ease of maintenance, you might want to create a custom post type for staff members, then display those custom posts on a staff page. But, you don’t want each staff member’s post to be accessible individually through a URL.

This was the case on a corporate site that I was working on when employees’ custom post type pages started showing up in Google search results.

Surprisingly, there isn’t a quick setting in the custom post type parameters to hide custom post type URLs without hiding the posts entirely from the front end. That’s what “‘publicly_queryable’ => false” does. It hides the custom post single posts, but it also hides them from any feeds they are in, so it’s only useful when the custom post type is used internally and never to be displayed on the front end.


The Solution

The best solution I’ve found is to redirect the single posts by using a code snippet in your theme’s functions.php file as follows:

// -------------------------------------------------
// HIDE STAFF SINGLE POSTS
// -------------------------------------------------
function cpt_redirect_post() {
  if ( is_singular( 'staff' ) ) {
    wp_redirect( home_url(), 301 );
    exit;
  }
}
add_action( 'template_redirect', 'cpt_redirect_post' );

Using our staff example, this code assumes you have a custom post type called “staff”, which you display on a page. But, you don’t want individual staff pages to be visible on the front end. This code simply redirects all “staff” posts to the home page. You can redirect to a 401 page if you prefer.

Search Engines

Remember to also remove these custom post types from your sitemap so they don’t show up in Google search. In Yoast, this can be done in Search Appearance -> Content Types -> Show Posts in search results (set to off).

I hope this was helpful to you. Let me know if you have comments or questions below! – Brian


Please Leave a Question or Comment

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Shares
%d bloggers like this: