WordPress自定义文章类型怎么自定义模板(含分类目录和文章模板),说到WordPress自定义文章类型,最近是用到很多,但是织梦调用不同的模板文件,今天给大家说一下WordPress自定义文章类型调用模板有一个默认规则。
WordPress自定义文章类型调用模板有一个默认规则,即优先调用当前主题目录下的single-[type_name].php
,这里的[type_name]
为自定义类型的名字。比如自定类型为product
,那么就优先调用single-product.php
;如果single-[type_name].php
不存在,则调用single.php
;single.php
不存在则调用index.php
对于自定义文章类型的列表页(分类目录)来说,则优先调用主题目录下的archive-[type_name].php
;archive-[type_name].php
不存在,则按顺序查找archive.php
、index.php
。
如果希望指定某个自定义文章类型调用某个模板,实现代码为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | /*调用指定的模板文件,以product自定义类型为例*/ add_filter( 'template_include', 'brain1981_include_template_function', 1 ); function brain1981_include_template_function( $template_path ) { if ( get_post_type() == 'product' ) { if ( is_single() ) { if ( $theme_file = locate_template( array ( 'single-product.php' ) ) ) { $template_path = $theme_file; } }elseif ( is_archive() ) { if ( $theme_file = locate_template( array ( 'archive-product.php' ) ) ) { $template_path = $theme_file; } } } return $template_path; } |
以上代码中可任意替换文件名single-product.php
和archive-product.php
为自己想要的。
不过以上只能为每个自定义类型指定一个任意模板,如果希望像页面page那样,在自定义文章类型的后台也能自由切换选择多款模板呢?
从WordPress 4.7开始这个变得非常容易。
只要在你的模板开头几行的注释中加入“Template Post Type:”这个标识参数,这个模板就会变成指定自定义类型的备选模板:
1 2 3 4 5 | /** * Template Name: Product - PDF Converter Master for Mac * Template Post Type: page, product ... */ |
这真的是很方便了!
参考:https://make.wordpress.org/core/2016/11/03/post-type-templates-in-4-7/