Redirect CPT single posts back to archive

In a recent project I created a custom post type for testimonials, however, these were only ever intended to be shown on an archive page, not as single posts. To prevent single posts from being accessible, I added the following code which redirects visitors to the post type archive if they attempt to visit a single post.

add_action( 'template_redirect', __NAMESPACE__ . '\\hide_single_testimonials' );
* We don't want to show single testimonials, only the archive.
* If someone tries to visit a single testimonial this action will ping them back to the testimonials archive.
* @since 1.0.0
function hide_single_testimonials() {
if ( is_singular( [ 'me_testimonials' ] ) ) {
wp_redirect( get_post_type_archive_link( 'me_testimonials' ), 301 );
view raw functions.php hosted with ❤ by GitHub

Reader Interactions

Leave a Reply

Your email address will not be published.