1

I'm currently using wp_safe_redirect() in a callback function that is hooked into the template_include filter. I would like to do my conditional statements here to determine whether the template should load based on user capabilities. If not, then redirect to home page. It looks like this:

public function my_load_template( $page_template ) {

    if ( is_singular( 'my_cpt' ) && is_user_logged_in()
        && current_user_can( 'update_core' ) ) {
        return plugin_dir_path( dirname( __FILE__ ) ) .  'public/templates/single-my_cpt.php';
    }
    else {
        wp_safe_redirect( home_url() );
        exit;
    }
}   

Hooked using add_filter( 'template_include', my_load_template' );

In the case that it redirects, I get a browser error saying the site "redirected you too many times." I suspect this may be a result of running the redirect during this filter.

I would like my conditional check for user capabilities to be as early as possible. So when is it safe to follow that with a redirect? Should I be doing a capability check and redirect in the single post template?

0

I've been going through action hooks and the earliest I've gotten it to work properly with my conditions for user and page type conditions is the wp action. Although, I am currently hooking it into template_redirect as it seems most appropriate and intended for this purpose according to the codex:

It is a good hook to use if you need to do a redirect with full knowledge of the content that has been queried.

Any attempt to redirect in an action that precedes wp in the order of [actions run] would cause problems, such as not being able to modify headers or the "redirected you too many times" error.

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.