【问题标题】:Show different page templates for custom post types为自定义帖子类型显示不同的页面模板
【发布时间】:2015-08-23 01:20:32
【问题描述】:

我正在为 wrpdress 使用自定义帖子类型 UI 插件,并创建了自定义“页面”。我已将这些页面设置为能够使用页面模板下拉列表,但想知道是否有人知道为不同帖子类型显示单独页面模板的方法?

【问题讨论】:

    标签: wordpress custom-post-type


    【解决方案1】:

    您将需要theme_page_templates 过滤器挂钩来删除您不想为每种帖子类型看到的模板。当加载模板时,包括在编辑屏幕中显示,返回的模板首先传递给这个函数:

    apply_filters ( 'theme_page_templates', array $page_templates, WP_Theme $this, WP_Post|null $post )
    

    要实现,您将使用如下代码:

    function filter_theme_page_templates( $templates, $theme, $post ){
        // make sure we have a post so we know what to filter
        if ( !empty( $post ) ){
    
            // get the post type for the current post
            $post_type = get_post_type( $post->ID );
    
            // switch on the post type
            switch( $post_type ){
                case 'custom-post-type':
                    // remove anything we don't want shown for the custom post type
                    // array is keyed on the template filename
                    unset( $templates['page-template-filename.php'] );
                    break;
                default:
                    // if there is no match it will return everything
                    break;
            }
        }
    
        // return the (maybe) filtered array of templates
        return $templates;
    }
    add_filter( 'theme_page_templates', 'filter_theme_page_templates', 10, 3 );
    

    【讨论】:

    • 嗨,这会涉及排除数组中的每个模板文件名吗?当我们达到 50 多个模板时会发生什么?这不费力吗?我希望为不同的cpt设置不同的子文件夹
    • 这就是它在 WordPress 中的工作方式。这可能有点费力,但根据我的经验,不应该有那么多模板,也不应该经常更改。如果你想让它编程,你可以将上面的代码作为插件的基础,让你通过 UI 控制它,但这显然超出了这个问题的范围。
    • 如果您想排除“所有内容”,只需为您不想显示的帖子类型返回一个空数组。或者,如果您只想要 1,您可以将其从 $templates 数组复制到一个新数组中并返回。
    • 我使用页面模板作为登陆页面,因此模板量很大
    • 取决于您的具体情况,但有一些主题,如 Divi,可让您为每页设置特定布局,但这可能不适用于您的用户。可以做你想做的事,上面的代码是起点,但这将是一些编程工作。祝你好运!
    猜你喜欢
    • 2014-01-15
    • 1970-01-01
    • 2016-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多