在WordPress主题中正确包含PHP文件的方法

3
我正在尝试开发一个需要使用大量PHP函数和自定义类的WordPress主题。
我想知道在WordPress中包含其他PHP文件的最佳实践是什么。例如:我是否需要使用以下方法列出每个要包含的文件:
  • include();
  • require_once()
  • 等等
当我查看其他开发人员的主题时,我从未遇到过一堆"include()语句,因此我相信我可能错过了某些执行这些包含的标准方法。

你可能会对WordPress主题开发中常见的错误感兴趣,可以查看这篇博客文章:http://scriptbaker.com/common-mistakes-in-wordpress-theme-development/ - Tahir Yasin
5个回答

15

您可以采用任何方法,但我建议您使用require来包含任何文件。

_s(也称为下划线)是WordPress的主题起始套件和默认主题,例如TwentyFourteen,TwentyThirteen等都使用require来包含文件。

参见在TwentyFourteen主题中使用的示例代码。

require get_template_directory() . '/inc/template-tags.php';

如果您正在为子主题进行操作,则需要使用stylesheet_directory而不是template_,例如:require get_stylesheet_directory() . '/folder/file.php'; - Asadullah

2

如果您正在使用子主题并需要从子主题文件夹加载php文件,则应使用get_stylesheet_directory()函数。get_stylesheet_directory()


如何实现它? - Fernando Torres

0

另一种方法是将文件指定并在functions.php中包含它,以避免冗余

例如,我的functions.php位于根目录中, 从/inc目录和functions目录获取文件。

include('inc/assets.php'); //Where i register all css and js
include('functions/index.php'); // Where are all functions are registered

在WordPress Codex中还有另一种方法https://codex.wordpress.org/Theme_Development#Including_Template_Files

<?php get_template_part('template-parts/blog', 'content'); ?>

还要查看WordPress组织主题文件文档https://developer.wordpress.org/themes/basics/organizing-theme-files/

assets (dir)
      - css (dir)
      - images (dir)
      - js (dir)
inc (dir)
template-parts (dir)
      - footer (dir)
      - header (dir)
      - navigation (dir)
      - page (dir)
      - post (dir)
404.php
archive.php
comments.php
footer.php
front-page.php
functions.php
header.php
index.php
page.php
README.txt
rtl.css
screenshot.png
search.php
searchform.php
sidebar.php
single.php
style.css

0
包含将会包含文件内容 需要则在找不到文件时抛出错误。 include_once 检查是否已经包含,如果没有,则进行包含。 require_once 与 include_once 相同,但是如果找不到文件,则会抛出错误。
如果您是编写该文件的人,应该使用include而不是include_once。
通常,我们使用include来包含不必要的文件。 对于重要文件,我们使用require。例如,footer.php不会使脚本停止,但core.php很重要。

0
为什么不把所有的包含文件都放到一个单独的文件(library.php)中,然后在你的主题中进行引用呢? 这样做的好处是如果你需要更改某个文件,你只需更改一个文件即可。此外,你还可以在library.php中使用条件标签(if..else)来针对特定页面包含特定文件。
我还建议您对重要文件使用require_once()函数,这样当文件丢失时会出现错误。如果没有错误,那么使用该文件的函数将产生多个错误。
另外,正如@Othman所建议的那样,您可以使用include来引用较不重要的文件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接