Redirect users on specific post category or category page

im trying to redirect users on specific categry with this hook:

// Show app-data posts only to app users
function user_redirect()
{
    if ( is_category( 'app-data' ) ) {
        $url = site_url();
        wp_redirect( $url );
        exit();
    }
}
add_action( 'the_post', 'user_redirect' );

But its not working and i dont know why. it redirect if the user if browsing the category. i want to redirect if the user is browsing the category or a post of that category

2 Answers
2

Why it’s not working?

There is one major problem with your code… You can’t redirect after any html content was already sent… Such redirect will be ignored…

So why is your code incorrect? Because of the_post hook. This hook is fired up when the object of post is set up. So usually it’s in the loop, which is much too late to do redirects…

So how to fix your code?

Use another hook.

Here is the list of available hooks fired up during typical request.

One of the best hooks for doing redirects (and commonly used for that) is template_redirect. As you can see it’s fired up just before getting header, so everything is already set up.

function redirect_not_app_users_if_app_data_category() {
    if ( (is_category( 'app-data' ) || in_category('app-data'))&& ! is_user_logged_in() ) {
        wp_redirect( home_url() );
        die;
    }
}
add_action( 'template_redirect', 'redirect_not_app_users_if_app_data_category');

Leave a Comment