当前浏览:首页 / WordPress钩子 / template_redirect

do_action( 'template_redirect' )

在确定要加载的模板之前触发

templatemore...


更多信息

  • 这个动作钩子在WordPress决定加载哪个模板页面之前执行。如果您需要在完全了解所查询内容的情况下进行重定向,那么可以使用它。
  • 加载不同的模板并不能很好地使用此动作挂钩。如果包含另一个模板,然后使用exit()(或die()),则不会运行后续的template_redirect挂钩,这可能会破坏站点的功能。相反,使用template_include过滤器钩子返回要使用的新模板的路径。这将允许在不干扰WordPress加载过程的情况下使用替代模板。

源码

查看源码 官方文档


更新日志

版本描述
1.5.0开始引入

使用示例

  • 示例1

    将现有页面重定向到其他页面:

    function custom_redirects() {
    
    	if ( is_front_page() ) {
    		wp_redirect( home_url( '/dashboard/' ) );
    		die;
    	}
    
    	if ( is_page('contact') ) {
    		wp_redirect( home_url( '/new-contact/' ) );
    		die;
    	}
    
    }
    add_action( 'template_redirect', 'custom_redirects' );
  • 示例2

    从Codex迁移的示例:

    以下示例将在尝试访问“goodies”页面时将所有未经身份验证的用户重定向到自定义“signup”页面。

    function my_page_template_redirect() {
        if ( is_page( 'goodies' ) && ! is_user_logged_in() ) {
            wp_redirect( home_url( '/signup/' ) );
            exit();
        }
    }
    add_action( 'template_redirect', 'my_page_template_redirect' );

    不要忘记在wp_redirect()之后调用exit()(或die())。

  • 示例3

    如果您需要从自定义插件中删除template_redirect,只需使用remove_action( 'template_redirect', 'function_to_remove' );这是不可能的。

    作为一种变通方法,您可以创建一个函数,以便在更早的时候钩住template_redirect操作,然后删除您试图删除的重定向。

    // remove a template redirect from within a custom plugin.
    add_action( 'template_redirect', 'remove_my_action', 5 );
    function remove_my_action(){
        remove_action('template_redirect', 'function_to_remove', 10 );
    }