Home > other >  WordPress how to redirect Private Custom Post Types
WordPress how to redirect Private Custom Post Types

Time:09-18

We have a WordPress website with a custom theme and we're using CPTs (Custom Post Types).

For some reason/s, when we set the CPT Visibility to Private, the pages are still available publicly but it's a completely empty document; no head data, no body data other than a string(n) "post_title" for example: string(9) "ade184065".

You can find a live example here:

https://www.gozoprime.com/gozo-properties/ade184065/

As you can see, it's a property listing website, and when a property is sold we set it as private, as we would still like to keep the data.

I really did my best to try and find what could be causing this, but after hours on-end, I'm not getting anywhere and there's nothing related online - so my thought is that we have a clash with our own custom code?

Disabling all plugins did not solve the issue either.

Has anyone encountered this problem before perhaps?

Note: I also tried to detect if post is private and manually redirect, but whatever happens is happening before the actual property page code is ran. So placing this code in content-single-cpt-name.php doesn't work:

// Check post status: Public | Private -> Redirect accordingly
if ( get_post_status ( get_the_ID() ) == 'private' ) { ...

Your help would be much appreciated!

CodePudding user response:

There are multiple ways you could solve this issue. Since, you haven't provided details about your cpt, i'd say, try to redirect the user if a post has private status. Again there are other ways to do it but you didn't give us more details on how you've setup your cpt.

In the following code, i'm using template_redirect action hook and wp_safe_redirect to redirect the user to the home_url. Feel free to change the home_url to whatever url you need to redirect the user to!

add_action('template_redirect', 'your_theme_private_posts_redirect');

function your_theme_private_posts_redirect()
{
    if (is_single() && 'private' == get_post_status(get_the_ID())) {
        wp_safe_redirect(home_url());
        exit();
    }
}

The code goes to the functions.php file of your active theme. Just tested it and it works fine!


UPDATE

Since you're using a custom theme, there might be other redirects that would prevent this functionality from executing properly. Therefore, you could add a priority, let's say 99, to the code i provided you with, and hopefully it'll solve the issue, like so:

add_action('template_redirect', 'your_theme_private_posts_redirect', 99);

function your_theme_private_posts_redirect()
{
    if (is_single() && 'private' == get_post_status(get_the_ID())) {
        wp_safe_redirect(home_url());
        exit();
    }
}
  • Related