【问题标题】:Single Post Template Override for Custom Post Type自定义帖子类型的单个帖子模板覆盖
【发布时间】:2021-04-01 16:47:37
【问题描述】:

我正在尝试确定一个独特的场景。我正在为已经存在的自定义帖子类型开发新模板。基本上,我们用一个新文件替换了 single-customposttype.php 文件。所有这一切都在顺利进行,除了一件事 - 他们有一篇属于他们想要保留 OLD 模板的自定义帖子类型的帖子。

所以有一个新的 single-customposttype.php 文件将用作该 CPT 的默认单一模板。

但我需要 ID #93 才能使用 OLD single-customposttype.php 模板。我希望只做 single-customposttype-93.php 可以解决问题,但事实并非如此。将另一个模板仅应用于一个帖子 ID 的最佳方法是什么?

提前致谢!

【问题讨论】:

    标签: wordpress wordpress-theming custom-post-type custom-wordpress-pages


    【解决方案1】:

    一直在处理自定义模板加载,这真的很简单!真的,您需要做的就是挂钩template_include 挂钩,并根据您想要的任何条件覆盖模板。

    该钩子接受一个参数,即要加载的$template 文件。然后,您可以使用任何您想要的条件并强制加载单独的文件。

    add_filter( 'template_include', 'custom_template_include', 99 );
    function custom_template_include( $template ){
        // For ID 93, load in file by using it's PATH (not URL)
        if( get_the_ID() === 93 ){
            // Note the file name can be ANYTHING, the WP auto-template names don't matter here
            $file = get_stylesheet_directory() . '/post-id-93-custom-template.php';
    
            // It's generally good to see if the file exists before overriding the default
            if( file_exists( $file ) )
                $template = $file;
        }
    
        // ALWAYS return the $template, or *everything* will be blank.
        return $template;
    }
    

    真的就这么简单!在自定义 PHP 文件中,您可以访问所有 WordPress 函数,就像使用默认模板一样。

    通常,您需要在模板上使用file_exists() 函数,以确保找到它,否则您将传递一个不存在的文件,并且该页面将无法加载。通过检查它是否存在,如果找不到(删除/重命名/移动等),它仍然会回退到旧模板

    另外,你总是需要在结尾加上return $template,否则任何使用 WordPress 模板系统的东西都会损坏。


    我在演示网站上做了一个简单的例子:

    政策是自定义帖子类型,cookie 政策正常加载。另一个使用与上面相同的代码进行修改(名称/ID 已更改为匹配),它正在加载一个包含该内容的简单 .php 文件。

    【讨论】:

    • 嗯。它看起来很简单,你的例子显然有效。但由于某种原因,它不适用于我的安装。我从您的代码中更改的唯一内容是文件名,它确实存在。让我相信我的安装中的某些东西可能会覆盖覆盖。有任何想法吗? (抱歉,由于保密协议,我无法显示安装)
    • 文件在正确的位置吗?上面的代码假定它位于主题目录的基础级别。你可以做var_dump(file_exists($file));,如果一切都好,它会吐出bool(true)。如果是,您可以尝试将函数的优先级从 99 更改为更高的值,9999999 - 主题中可能有某些内容或稍后在 template_include 上运行某些内容的插件比99
    猜你喜欢
    • 1970-01-01
    • 2011-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多