Which hook should be used to add an action containing a redirect?

The question:

I want to build a plugin that grabs certain url params from the query string to build a new query string for the same page. I’m following the excellent the Professional WordPress Plugin Development book, but I’m not sure which hook to use for this action. Here is my action function:

add_action( 'init', 'tccl_redirect' );
function tccl_redirect() {
    header ( "Location: http://www.mysite.com/$mypage?$newparam=$newvalue" );
?>

Which hooks are suitable for header redirects?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Like kaiser answered template_redirect hook is indeed appropriate for redirects.

Also you should use wp_redirect() function, rather than setting header.

Method 2

I’d say template_redirect. But take a look at the Action Reference.

Example

Don’t forget to exit() on redirect.

/**
 * This example redirects everything to the index.php page
 * You can do the same for the dashboard with admin_url( '/' );
 * Or simply base the redirect on conditionals like 
 * is_*() functions, current_user_can( 'capability' ), globals, get_current_screen()...
 * 
 * @return void
 */
function wpse12535_redirect_sample() {

    exit( wp_redirect( home_url( '/' ) ) );

}

add_action( 'template_redirect', 'wpse12535_redirect_sample' );

Method 3

But i would say this example from kaiser cannot working, because after an redirect this hook template_redirect works again and again, you will have an endless forwarding !

Better is to check, if you’re already on the homepage, like this:

function wpse12535_redirect_sample() {

    $current_url = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
    $site_url = get_bloginfo('siteurl') . "/";

    if($current_url != $site_url)       
      exit( wp_redirect( home_url( '/' ) ));    

}
add_action( 'template_redirect', 'wpse12535_redirect_sample');

Works for me fine. Any suggestions? Regards!


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment