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

问题描述 投票:0回答:2

我想重构我正在创建的 WordPress 主题中的模板文件。现在,诸如

single.php
archive.php
之类的文件位于我主题的根级别。我想将它们移动到自己的文件夹中 - 比如说一个名为
pages
的文件夹。所以它看起来像这样:

mytheme 
  -- pages
      -- archive.php
      -- single.php
  -- functions.php
  -- index.php
  -- style.css

这可能吗?如果是的话,怎么办?

谢谢。

php wordpress wordpress-theming
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


2
投票

对我来说有效
(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
文件夹中,只需从
index
中删除
$predefined_names

幸运的黑客!

© www.soinside.com 2019 - 2024. All rights reserved.