php - 使用 Timber Twig 在 Wordpress 中自定义 php 文件目录

标签 php wordpress twig php-7 timber

我正在使用 Timber使用 Wordpress(版本 5.4.2)。我已经安装了 Timber 的 starter theme作为样板文件。

Timber 利用 Wordpress 模板层次结构允许您创建 custom PHP file for a given route .

Page.php(Timber 入门主题中的默认值)

/**
 * The template for displaying all pages.
 *
 * This is the template that displays all pages by default.
 * Please note that this is the WordPress construct of pages
 * and that other 'pages' on your WordPress site will use a
 * different template.
 *
 * To generate specific templates for your pages you can use:
 * /mytheme/templates/page-mypage.twig
 * (which will still route through this PHP file)
 * OR
 * /mytheme/page-mypage.php
 * **(in which case you'll want to duplicate this file and save to the above path)**
 *
 * Methods for TimberHelper can be found in the /lib sub-directory
 *
 * @package  WordPress
 * @subpackage  Timber
 * @since    Timber 0.1
 */

$context = Timber::context();

$timber_post = new Timber\Post();

$context['post'] = $timber_post;

Timber::render( [ 'page-' . $timber_post->post_name . '.twig', 'page.twig' ], $context );

根据 page.php 和 Timber 文档中的评论,我可以创建一个自定义 PHP 文件来加载给定页面的模板,方法是在主题的根目录中创建它 (mytheme/my-custom -php-file.php)

但我会为我正在处理的项目创建很多自定义 PHP 文件 - 如果我将它们全部放到主题的根目录中,这将非常困惑且难以管理。

我想将这些文件放入它们自己的目录 mytheme/src/。前任。 mytheme/src/my-custom-php-file.php.

目前,Timber/Wordpress 无法识别此目录中的此文件。

在 Timber 和/或 Wordpress 中的哪个目录中查找页面的 PHP 文件已定义,我如何更新它以指示 mytheme/src/

最佳答案

这是可能的,但与您的预期略有不同。您必须将所有与主题相关的文件放入子文件夹,包括functions.phpstyle.css。 WordPress 识别子文件夹中的主题。

下面是一个可能的结构:

.
└── wp-content/themes/mytheme/
    ├── theme/
    │   ├── functions.php
    │   ├── index.php
    │   ├── page.php
    │   ├── single.php
    │   └── style.css
    ├── vendor/
    ├── views/
    ├── .gitignore
    ├── composer.json
    ├── package.json
    └── README.md

我们将 WordPress 需要的模板文件放入 theme 子文件夹中。您仍然可以将 views 文件夹放在主题根目录中,因为 Timber 还会在该文件夹中查找 Twig 模板。

在您的 functions.php 文件中,您需要来自父文件夹的 Composer 依赖项:

require_once dirname( __DIR__ ) . '/vendor/autoload.php';

并且可能还有其他一些地方您必须更新路径。

我们目前正在考虑将其设为 Timber Starter Theme 的默认值(参见 this pull request)。

关于php - 使用 Timber Twig 在 Wordpress 中自定义 php 文件目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62542638/

相关文章:

php - 填充数组并通过 AJAX 发送的脚本

php - PHPGraphlib PHP 图表演示黑屏

php - 将 JSON 数据输入 MySQL

php - 为每个 Twig 设置翻译域

javascript - HTML看不到Javascript代码; php代码中的执行没有错误就中断了?

php - 多域不同静态页面

wordpress - 如何找到 EC2 实例上托管的 WordPress 网站的 FTP 凭证?

mysql - 如何使用 Wordpress UpdraftPlus 修复 MySql 数据库恢复错误 : Error Code: 1067. 'user_registered' 的默认值无效

symfony - 在 Symfony 4 或 Symfony 5 新项目上安装 twig/extensions

symfony - 使用变量作为 twig 中的散列键(作为 path() 或 |trans 中的参数)