Redirect users on specific post category or category page

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');