問題描述

我想構建一個插件,從查詢字符串中獲取某些 url 參數,為同一頁面創建一個新的查詢字符串。我遵循了專業的 WordPress 插件開發書,但我不知道使用哪個鈎子來執行此操作。這是我的動作功能:

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

哪些鈎子適合標頭重定向?

最佳解決方案

像 kaiser 回答 template_redirect 鈎子確實適合重定向。

還應該使用 wp_redirect()功能,而不是設置標題。

次佳解決方案

我會説 template_redirect 。但是看看 Action Reference

例子

不要忘記 exit()重定向。

/**
 * 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' );

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。