将WordPress主题模板文件移动到子目录

5
我希望重新组织我正在创建的WordPress主题中的模板文件。目前,像single.phparchive.php这样的文件在我的主题根目录下。我想将它们移动到自己的文件夹中——比如一个名为pages的文件夹。这样它会看起来像这样:
mytheme 
  -- pages
      -- archive.php
      -- single.php
  -- functions.php
  -- index.php
  -- style.css

这有可能吗?如果可以,怎么做呢?
谢谢。
2个回答

4
你可以使用single_template 过滤器和{$type}_template 过滤器来处理归档、分类等方面的内容。
我认为你需要的是类似这样的东西:
function get_new_single_template( $single_template ) {
  global $post;
    $single_template = get_stylesheet_directory() . '/pages/single.php';
  return $single_template;
}
add_filter( 'single_template', 'get_new_single_template' );

function get_new_archive_template( $archive_template ) {
  global $post;
    $archive_template = get_stylesheet_directory() . '/pages/archive.php';
  return $archive_template;
}
add_filter( 'archive_template', 'get_new_archive_template' );

这是针对您的functions.php文件的操作。

1

对我来说,(type)_template_hierarchy 钩子很有效。

文档:https://developer.wordpress.org/reference/hooks/type_template_hierarchy/

长话短说

它是做什么的?WordPress正在寻找所有可以匹配请求URL的模板文件名。然后它按优先级选择最好的一个。但是您可以在此之前更改这些文件名的数组。

WordPress中有很多模板名称,在这里列出

要替换单个文件位置,例如只有 index.php,您可以使用以下代码:

// functions.php

add_filter('index_template_hierarchy', 'replace_index_location');

function replace_index_location($templates) {
    return array_map(function ($template_name) {
        return "pages/$template_name";
    }, $templates);
}

看一下:

  • 首先,我们添加钩子来替换索引文件位置。
  • 函数replace_index_location接收所有候选项。尝试var_dump($templates)变量,以查看其中的内容。
  • 然后,将此数组简单映射到另一个数组中,为每个文件名添加“pages”文件夹或任何其他文件夹。所有这些路径都是相对于主题文件夹的。

但是,如果您需要移动所有文件,而不仅仅是index.php呢?

解决方案

我们来看看:

// functions.php

function relocate() {
    // All available templates from 
    // https://developer.wordpress.org/reference/hooks/type_template_hierarchy/#description
    $predefined_names = [
        '404', 'archive', 'attachment', 'author', 'category', 
        'date', 'embed', 'frontpage', 'home', 'index', 'page', 
        'paged', 'privacypolicy', 'search', 'single', 'singular', 
        'tag', 'taxonomy', 
    ];

    // Iteration over names
    foreach ($predefined_names as $type) {
        // For each name we add filter, using anonymus function
        add_filter("{$type}_template_hierarchy", function ($templates) {
            return array_map(function ($template_name) {
                return "pages/$template_name";
            }, $templates);
        });
    }
}

// Now simply call our function
relocate();

这段代码使我们的文件树看起来像这样:
mytheme 
  -- pages
      -- index.php // index also here
      -- archive.php
      -- single.php
  -- functions.php
  -- style.css

如果您不需要将index.php放在pages文件夹中,只需从$predefined_names中删除index即可。
祝您好运!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接