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

我正在Timber和Wordpress(版本5.4.2)一起使用。我已经安装了Timberstarter theme作为样板。

Timber利用Wordpress模板层次结构来创建custom PHP file for a given route

Page.php(木材入门主题中的默认设置)

/**
 * 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文档中的注释,我可以通过在主题(mytheme/my-custom-php-file.php)的根目录中创建一个自定义PHP文件来为给定页面加载模板

>

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

相反,我想将这些文件放到它们自己的目录mytheme/src/中。例如mytheme/src/my-custom-php-file.php

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

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

iCMS 回答:使用Timber Twig在Wordpress中自定义php文件目录

这是可能的,但与您预期的有所不同。您必须将所有与主题相关的文件放入一个子文件夹,包括 functions.php style.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需要的模板文件放入主题子文件夹。您仍然可以将 views 文件夹放在主题根目录中,因为Timber也在该文件夹中查找Twig模板。

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

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

也许还有其他一些地方需要更新路径。

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

,

查看template_include文档,因为我认为您也许可以执行以下操作:

// functions.php
add_filter( 'template_include',function( $template ) {
    return 'src/' . $template;
},99 );

OR

// functions.php
add_filter( 'template_include',function( $template ) {
    if (// some condition) {
        return 'src/' . $template;
    }
    
    return $template;
},99 );
本文链接:https://www.f2er.com/2071512.html

大家都在问