首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Timber的Wordpress中的自定义php文件目录

使用Timber的Wordpress中的自定义php文件目录
EN

Stack Overflow用户
提问于 2020-06-23 19:48:34
回答 2查看 1.2K关注 0票数 3

我使用的是木料和Wordpress (5.4.2版)。我已经安装了木材的起始主题作为样板。

木材利用Wordpress模板层次结构,允许您创建一个给定路由的自定义PHP文件

Page.php (木材起始主题中的默认主题)

代码语言:javascript
复制
/**
 * 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/

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-06-25 13:38:34

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

下面是一个可能的结构的样子:

代码语言:javascript
复制
.
└── 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需要的模板文件放入主题子文件夹中。您仍然可以将视图文件夹放在主题根中,因为Timber还可以在该文件夹中查找Twig模板。

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

代码语言:javascript
复制
require_once dirname( __DIR__ ) . '/vendor/autoload.php';

也许还有其他地方你必须更新路径。

我们目前正在考虑将此设置为木材起动机主题的默认设置(参见此拉请求)。

票数 2
EN

Stack Overflow用户

发布于 2020-06-23 21:18:13

查看template_include文档,因为我认为您可能可以这样做:

代码语言:javascript
复制
// functions.php
add_filter( 'template_include', function( $template ) {
    return 'src/' . $template;
}, 99 );

代码语言:javascript
复制
// functions.php
add_filter( 'template_include', function( $template ) {
    if (// some condition) {
        return 'src/' . $template;
    }
    
    return $template;
}, 99 );
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62542638

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档