将自定义模板分配给静态博客页面

Assigning custom templates to a static blog page

我正在寻找在 WordPress 中为博客页面创建自定义布局的最佳解决方案。

您通常会 select 从管理中的模板 metabox 自定义页面模板来更改页面布局,这不适用于静态博客页面。

默认情况下,WordPress 模板层次结构会查找 home.php 然后 index.php 进行显示,它根本不会检查自定义页面模板。 View the Template Hierarchy here. WordPress codex 还对博客页面进行了说明:

不要为此页面使用自定义页面模板。模板文件 home.php 或 index.php 将用于在主题中生成此页面。

我个人觉得这很奇怪。如果有一个页面我想有不同的布局可用它是博客列表。

我目前唯一的解决方案是创建一个名为 "Blog Layouts" 的新元数据框。我的 home.php 然后根据 metabox 设置的值加载自定义模板部分。虽然我确信这会起作用,但知道 WordPress 提供了它自己的用于设置页面模板的元数据框,感觉有点老套。

如果有人有更好的建议,我很乐意阅读。

如果站点只有页面和帖子,那么只要您有页面的 page.php 文件,只需编辑 index.php 即可。无需创建另一个模板文件。

您可以为特定类别创建特定模板。

http://codex.wordpress.org/Category_Templates

最好的办法是对您想要不同样式的帖子进行分类,然后为该类别创建一个模板。

您可以利用模板 metabox。

<?php

function get_blog_template() {
    // Get the template metabox value from the page used as post archive. 
    $template_file = get_post_meta(get_option('page_for_posts'), '_wp_page_template', true);
    if ($template_file == 'templates/blog-small.php') {
        get_template_part('templates/blog', 'small');
    } elseif ($template_file == 'templates/blog-wide.php') {
        get_template_part('templates/blog', 'wide');
    } else {
        echo 'Sorry, no template is found';
    }
}

?>

然后调用home.php

中的函数
<?php get_blog_template(); ?>