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

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() );
    add_action( 'template_redirect', 'redirect_not_app_users_if_app_data_category');

  • 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() );

Related Questions