livy/plumbing-templates

将您的页面(或自定义帖子类型)模板放在更好的目录中。与 Sage 兼容!

2.0.0 2021-10-31 19:39 UTC

This package is auto-updated.

Last update: 2024-08-29 04:31:36 UTC


README

此工具为您提供了一种改进自定义页面模板文件组织方式的方法。对于 Wordpress 4.7+,您还可以使用其他帖子类型的模板。

它提供了一些合理的默认设置,应该适用于大多数情况,但也可以进行大量配置。自带对 Sage 10 的内置支持。如果您想为具有非标准模板组织的其他框架添加内置支持,请提交 PR 或问题。

用法

首先,安装此包

composer require livy/plumbing-templates

然后在早期运行的位置调用此工具(例如,在 functions.php 中)

Livy\Plumbing\Templates\register_template_directory('custom-templates');

默认情况下,此包假定您正在更改 page 帖类型的模板,但您可以通过传递第二个参数来指定任何帖子类型

// Define templates for the `event` post type:
Livy\Plumbing\Templates\register_template_directory('event-templates', 'event');

通常,您会希望将其包装在一个动作调用中,以确保它运行得足够早,例如:

add_action('init', function () {
    Livy\Plumbing\Templates\register_template_directory('event-templates', 'event');
});

高级用法

此包具有许多其他选项,允许您自定义其行为。您可以使用项目过滤器来执行此操作,但一次性传递所有参数可能更容易。为此,请使用 setup_template_location() 而不是 register_template_directory()

Livy\Plumbing\Templates\setup_template_location([
    'paths' => [ 'event-templates' ],
    'post_type' => 'event',
]);

...将产生与上面示例相同的效果。

pathspost_type 键必须定义,否则不会发生任何操作。

选项

以下是此包理解的所有选项的列表。

  • paths 数组 - 一个路径数组(相对于模板根目录)用于搜索模板。默认:空数组。
  • post_type 字符串 - 要使用这些模板的帖子类型。默认:page
  • filename 字符串 - 搜索模板时匹配的文件名。可以是字符串、简单的 glob(例如,*.ext)或正则表达式。默认:*.php
  • template_root 字符串 - 模板根目录,是所有模板路径相对于的目录。您可能不需要修改此值。默认:由 get_stylesheet_directory() 输出。
  • parent_template_root 字符串 - 与 template_root 相同,但对于潜在父主题中的模板。如果没有父主题,则忽略。您可能不需要修改此值。默认:由 get_template_directory() 输出。
  • contains 字符串 - 模板必须包含的字符串。也可以是正则表达式。用于识别哪些文件是模板。默认:Template Name:
  • name_regex 字符串 - 用于从模板内容中获取模板名称的正则表达式。默认:/Template Name: ?(.+)/
  • post_type_regex 字符串 - 用于确定模板是否适用于特定帖子类型的正则表达式。%post_type% 将在运行时替换为 post_type 选项的值。默认:/Template Post Type:.*%post_type%(?=(?:,|$))/m

Acorn 和 Sage

如果您使用的是 Sage starter theme 的 v10+ 版本 或在其他方面使用 Acorn,您知道您的模板存储在一个略微非标准的位置。幸运的是,如果它检测到您使用 Acorn,此包 会友好地修改默认设置