要在WordPress主题中调用某个PHP文件,可以使用get_template_part()函数。

get_template_part()函数用于获取主题目录中指定的PHP文件,它用于加载 WordPress 主题中的另一个模板文件,可以让你更好地组织和重用你的主题文件。
get_template_part()函数用法参考:WordPress 中 get_template_part 函数用法详解
get_template_part() 函数有两个参数:
$slug:用于指定要加载的模板文件的名称,可以包含子目录,但不需要包含文件扩展名。如果需要在主题根目录中加载名为header.php的模板文件,则可以使用$slug = 'header'。$name(可选):用于指定一个更具体的名称,用于区分不同的模板文件。如果在header.php中还有其他变体,例如header-home.php、header-blog.php等,可以使用$name参数来加载这些变体。如果不需要区分不同的模板文件,则可以省略$name参数。
下面看一些示例:
加载主题中的 header.php 文件:
get_template_part( 'header' );加载主题中的 header-home.php 文件:
get_template_part( 'header', 'home' );加载主题中的 partials/sidebar.php 文件:
get_template_part( 'partials/sidebar' );加载主题中的 content.php 文件,并传递一些变量:
$post_type = get_post_type(); get_template_part( 'content', $post_type );需要注意的是,get_template_part() 函数会自动加载与当前页面相关的特定模板文件。例如,在单篇文章页面中,如果没有指定 $slug 和 $name 参数,则默认加载 single.php 文件。在分类页面中,则默认加载 category.php 文件。因此,get_template_part() 函数可以帮助你轻松地编写更加灵活和可重用的 WordPress 主题代码。
作者:牛奇网,本站文章均为辛苦原创,在此严正声明,本站内容严禁采集转载,面斥不雅请好自为之,本文网址:https://www.niuqi360.com/wordpress/how-does-wordpress-theme-use-a-certain-php-file/