admin管理员组文章数量:1122846
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: /$mypage?$newparam=$newvalue" );
?>
Which hooks are suitable for header redirects?
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?
Share Improve this question asked Mar 20, 2011 at 12:26 jnthnclrkjnthnclrk 1,8454 gold badges25 silver badges52 bronze badges 5 |3 Answers
Reset to default 18Like kaiser answered template_redirect
hook is indeed appropriate for redirects.
Also you should use wp_redirect()
function, rather than setting header.
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' );
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!
本文标签: plugin developmentWhich hook should be used to add an action containing a redirect
版权声明:本文标题:plugin development - Which hook should be used to add an action containing a redirect? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736282450a1926648.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
template_redirect
would also be my suggestion. – t31os Commented Mar 20, 2011 at 14:03