文章目录[隐藏]
最近在改造 twentyseventeen 主题,这个主题中使用到了很多模板文件,比如文章模板:template-parts/post/content.php
,页脚模板:template-parts/footer/site-info.php
等等,并且使用了get_template_part()
函数来加载这些模板文件。使用这个函数可以利用子主题来直接重载并自定义父主题的模板内容,这里就记录一下这个函数的简单用法。
get_template_part()
这个函数的参数如下:get_template_part( string $slug, string $name = null )
,其中 $slug
参数是必须的,用于指定模板文件的路径和文件名,而 $name
则是指定专用模板文件的名称,最终加载的文件为:“$slug-$name.php
”。下面给出几个示例来说明一下。
1.要加载主题根目录下 template-parts/post/content.php
模板文件(在子文件夹中),写法是:
get_template_part( 'template-parts/post/content', 'none' );
或者是
get_template_part( 'template-parts/post/content' );
2.要加载主题根目录下 template-parts/footer/site-info.php
模板文件(在子文件夹中),则是:
get_template_part( 'template-parts/footer/site', 'info' );
3.要加载主题根目录下的 comment-page.php
模板文件,则是:
get_template_part( 'comment', 'page' );
4.对于父主题和子主题中模板文件的加载优先级,若主题目录是“wp-content/themes
”,父主题目录是“wp-content/themes/twentyseventeen
”,子主题目录是“wp-content/themes/twentyseventeen-child
”,对于第2点中的代码:
get_template_part( 'template-parts/footer/site', 'info' );
它的加载优先级为:
wp-content/themes/twentyseventeen-child/template-parts/footer/site-info.php
wp-content/themes/twentyseventeen/template-parts/footer/site-info.php
wp-content/themes/twentyseventeen-child/template-parts/footer/site.php
wp-content/themes/twentyseventeen/template-parts/footer/site.php
它会自上而下地检查这个文件是否存在,如果存在就加载此文件,并停止检查。你会发现,它是优先加载子主题的相应模板文件,所以,要想自定义模板文件,最好的方法就是照着父主题中该模板文件所在的路径,在子主题的相同路径下新建一个同名文件,这样子就可以重载父主题中的模板文件了。
总结
get_template_part()
函数对于自定义子主题模板文件很有用,但是!如果父主题中没有使用该函数来加载模板文件,那就不能使用这个方法来重载模板文件。
参考
get_template_part() | Function | WordPress Developer Resources
本作品由 sunriseydy 采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。
文章内容如未说明均为原创,欢迎转载,但请注明原作者(sunriseydy)和原文链接(https://blog.sunriseydy.top/technology/wordpress/wordpress-get_template_part/)
部分来自互联网的文章,如有侵权,请联系我,24小时内删除,谢谢
感谢您的支持,SunriseYDY 会继续努力的!



打开支付宝扫一扫,即可进行扫码打赏哦
日出一点一 | 在探索的路上永不止步