据我了解,在开发主题时,functions.php 会包含在每个 WordPress 页面中,并且应该包含所有主题逻辑。
主题的函数文件包含在每个请求中,但它不应包含所有主题的逻辑。如何组织主题的非模板文件取决于您,但您应该避免尝试将所有代码都塞进函数文件中。
我查看了我下载的主题的functions.php,它有超过 6,000 行。
不幸的是,对于主题开发人员来说,将所有代码转储到函数文件中并将其变成一场大的程序噩梦是很常见的。不要以此作为应该如何做事的例子。
像组织其他项目一样组织您的主题文件。我个人喜欢在开发主题时坚持PSR standards。我的函数文件通常只包含一些常量,一个PSR-4 autoloader 和一个初始化。例如:
// Const
define('MYPROJECT_VERSION', '1.0.3');
define('MYPROJECT_BUILD', 169);
// Autoloader (PSR-4)
// Adapted from https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md
spl_autoload_register(function ($class) {
// Project namespace
$prefix = 'MyProject\\';
// Base directory for the namespace prefix
$base_dir = __DIR__ . '/core/';
// Does the class use the namespace prefix
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) {
return;
}
// Get the relative class name
$relative_class = substr($class, $len);
// Replace the namespace prefix with the base directory, replace namespace
// separators with directory separators in the relative class name, append
// with .php
$file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
// If the file exists, require it
if (file_exists($file)) {
/** @noinspection PhpIncludeInspection */
require $file;
}
});
// Initialize
\MyProject\MyTheme::init();
// End of file
每次加载页面时都要读取“安装逻辑”、类定义等,这不是非常低效吗?
如果您使用自动加载器,则只会包含您使用的类。如果您担心 PHP 通常需要在每个请求上解析源文件,请查看 OPCache。
关于“安装逻辑”,可以分别使用after_switch_themes和switch_themes钩子进行安装和卸载。
add_action('after_switch_theme', function() {
// Install
});
add_action('switch_theme', function() {
// Uninstall
});