WordPress 4.7将增加文章模板功能

分享本文:
wp-47-post-templates

WordPress允许用户自定义页面模板,已经有12年的历史了,用户使用该功能可以给特定页面设置不一样的网页布局。在WordPress 4.7中,这一功能将被扩展到文章,以及更多的文章类型。WordPress中文网今天就给你做个详细介绍。

WordPress文章模版

在WordPress 4.7以前的版本中,模板功能仅仅局限于页面使用。利用这一功能,用户可以给页面选择使用各种不同预定义的模板。但其他类型的文章,无法使用这一功能。

WordPress 4.7新版本中,通过将页面模板扩能扩展给所有类型的文章,WordPress的模板体系的灵活性进一步得到增强。

除了在文件头部增加 Template Name 参数外,你还需要在这里指定 Template Post Type: post, foo, bar 。下面是一个例子:

<?php

/*
Template Name: Full-width layout
Template Post Type: post, page, product
*/

// ... 模板代码

这样,你就可以在 post(文章),page(页面),product(产品) 等类型的文章中选择使用这个名字为 Full-width layout(全宽布局) 的页面模板。

只要你的主题中有一个适合文章的模板,那么在后台文章编辑页面就会出现这个“Post Attributes”选项框。这个“Post Attributes”标题,可以在注册文章类型的时候进行定义。

我们来看一下实际效果:

wp-post-attributes

回溯兼容

假如说你想要公开发布一个WordPress主题,那么WordPress 4.7之前的版本将会忽略其中的 Template Post Type 参数,在页面模板中显示出这些模板来,哪怕这个模板中已经限制仅适用于正常文章(post)。

要防止这种情况发生,你需要钩住这个 theme_page_templates 过滤器,让它来把该模板排除在外。下面是代码示例:


/**
* 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' );

这样,既可以在WordPress 4.7中使用自定义文章模板功能,又可以回溯兼容以前的版本。

注意,现在这个 theme_page_templates 实际上是动态的 theme_{$post_type}_templates 过滤器。动态部分是指 $post_type ,是模板支持的文章类型。比如,你可以钩住 theme_product_themplates 来过滤 product 文章类型的模板。

要进一步了解WordPress 4.7的这个文章模板新功能,参考这里 #18375

 

分享本文:


评论: WordPress 4.7将增加文章模板功能

发表一下评论

邮箱地址不会被公开。 必填项已用*标注