2

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

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');
  • 1
    The question asks to redirect if a user is trying to view the category or any post in that category, so you need to check both cases. Changing the condition to if( !is_user_logged_in() && ( is_category( 'app-data' ) || in_category( 'app-data' ) ) ) should do it. – Andy Macaulay-Brook Jun 22 '18 at 18:18
  • @AndyMacaulay-Brook good point :) – Krzysiek Dróżdż Jun 22 '18 at 18:23
  • I thought it was silly adding my own answer just to make this point, so if you update yours with this and ping me I'll upvote you :-) – Andy Macaulay-Brook Jun 22 '18 at 18:27
2

change your hook name the_post to template_redirect

add_action( 'template_redirect', 'wpse_restrict_catgorey');
function wpse_restrict_catgorey(){

  if( ! is_user_logged_in() && is_category( 'app-data' ) ) {
    wp_redirect( home_url() );
    exit;
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.