参考:https://make.wordpress.org/core/2016/11/03/post-type-templates-in-4-7/
WordPress已支持自定义页面模板超过12年,允许开发人员为特定页面创建各种布局。虽然此功能非常有用,但它始终局限于“页面(page)”帖子(post)类型,而不可用于其他帖子类型。现在使用WordPress 4.7他做出了改变。
通过为所有帖子类型打开页面模板功能,模板层次结构的灵活性不断提高。下面是方法。
除Template Name
标头,由模板所支持的类型可以使用此方法指定可以使用此模板的文章类型Template Post Type: post, foo, bar
。这里有一个例子:
<?php
/*
Template Name: Full-width layout
Template Post Type: post, page, product
*/
// … your code here
这样,您就可以为帖子,页面和产品选择此模板。
当至少一个模板存在一个文章类型,“发布属性”元框会在后端显示,而不需要增加对文章类型支持'page-attributes' 或其他任何东西。“后属性”标签可以为每个文章类型类型,使用定制'attributes'注册后类型时标签。
Backward Compatibility
Let’s say you want to publicly release a theme with support for post type templates. WordPress versions before 4.7 will ignore the Template Post Type
header and show the template in the list of page templates, even though it only works for regular posts. To prevent that, you can hook into the theme_page_templates
filter to exclude it from the list. Here’s an example:
/** * Hides the custom post template for pages on WordPress 4.6 and older * * @param array $post_templates Array of page templates. Keys are filenames, values are translated names. * @return array Filtered array of page templates. */ function makewp_exclude_page_templates( $post_templates ) { if ( version_compare( $GLOBALS['wp_version'], '4.7', '<' ) ) { unset( $post_templates['templates/my-full-width-post-template.php'] ); } return $post_templates; } add_filter( 'theme_page_templates', 'makewp_exclude_page_templates' );
That way you can support custom post type templates in WordPress 4.7 and beyond while maintaining full backward compatibility.
Note that theme_page_templates
is actually a dynamic theme_{$post_type}_templates
filter. The dynamic portion of the hook name, $post_type
, refers to the post type supported by the templates. E.g. you can hook into theme_product_templates
to filter the list of templates for the product
post type.