钩子文档

template_include

💡 云策文档标注

概述

template_include 是一个 WordPress 过滤器钩子,用于在包含当前模板文件之前修改其路径。它允许开发者覆盖 WordPress 的默认模板行为,实现自定义模板加载逻辑。

关键要点

  • template_include 钩子在 WordPress 包含预定模板文件之前执行,参数为模板路径字符串。
  • 可用于根据条件(如页面 slug 或 URL 参数)动态切换模板文件。
  • 建议在自定义函数中检查新模板文件是否存在,并妥善处理未找到的情况。

代码示例

add_filter( 'template_include', 'portfolio_page_template', 99 );
function portfolio_page_template( $template ) {
    if ( is_page( 'portfolio' )  ) {
        $new_template = locate_template( array( 'portfolio-page-template.php' ) );
        if ( '' != $new_template ) {
            return $new_template ;
        }
    }
    return $template;
}

注意事项

使用 template_include 时,建议为新模板使用不同变量,检查文件是否存在,若不存在则返回原始模板路径以避免错误。


📄 原文内容

Filters the path of the current template before including it.

Parameters

$templatestring
The path of the template to include.

More Information

This filter hook is executed immediately before WordPress includes the predetermined template file. This can be used to override WordPress’s default template behavior.

Source

$template = apply_filters( 'template_include', $template );

Changelog

Version Description
3.0.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    This example includes a new template on a page called ‘portfolio’ if the new template file was found.

    add_filter( 'template_include', 'portfolio_page_template', 99 );
    function portfolio_page_template( $template ) {
        if ( is_page( 'portfolio' )  ) {
            $new_template = locate_template( array( 'portfolio-page-template.php' ) );
    	if ( '' != $new_template ) {
    	    return $new_template ;
    	}
        }
        return $template;
    }

  2. Skip to note 4 content

    /**
    * multiple custom routing with one page
    */
    add_filter( 'template_include', 'wpdocs_include_template_files_on_page' );
    
    function wpdocs_include_template_files_on_page( $template ) {
    
    	$action = isset( $_GET['action'] ) ? $_GET['action'] : 'list';
    
    	switch ( $action ) {
    
    		case 'add-list' :
    			$template = __DIR__ . 'views/address-new.php';
    			break;
    
    		case 'edit-list' :
    			$template = __DIR__ . 'views/address-edit.php';
    			break;
    
    		case 'view-list' :
    			$template = __DIR__ . 'views/address-view.php';
    			break;
    
    		default :
    			$template = __DIR__ . 'views/address-list.php';
    			break;			
    	}
    
    	return $template;
    }