How to disable single page for custom post type

How to disable single page for custom post type

One of the WordPress hooks where we can perform a redirect is template_redirect. In it, we’ll place our check and perform a redirect to the homepage.

add_action('template_redirect', function()
{
	if(is_singular('fruit'))
	{
		wp_redirect( home_url(), 301 );
		exit;
	}
});

Using an if condition and the WordPress tag is_singular, we check whether the user is currently viewing a single post page of the "fruit" post type. If so, we use the wp_redirect function, passing the homepage URL as the first parameter and the redirect status code as the second.

Alternative implementation:

add_filter('single_template', function($template)
{
	global $post;

	if($post -> post_type == 'fruit' && $post -> ID == 56)
	{
		wp_redirect( home_url(), 301 );
		exit;
	}
	return $template;
});

In this case, we use the single_template filter, which not only allows us to perform a redirect, but also — if needed — change the template file used to render the single post page.

Note that we’ve made the condition slightly more complex by restricting the redirect to only the post with ID 56.

That’s all.

Are you having problems with your WordPress site? Do you need additional functionality? A custom plugin or a new page?
Then write to me via the feedback form, and I will try to help you.

Write a comment

Your email address will not be published. Required fields are marked *