如果想为wordpress的分类分别设置不同的文章样式,可以通过自定义模板的方式实现。比如,我想为“免费资源”分类的文章设置与其它分类不同的模板。可以这样做:
一、先为“免费资源”分类创建一个新的文章模板:single-free.php,并将其放到当前主题根目录中。
二、添加以下代码到当前主题的 functions.php 文件中:
- add_action('template_include', 'load_single_template');
- function load_single_template($template) {
- $new_template = '';
- // single post template
- if( is_single() ) {
- global $post;
- // 'wordpress' is category slugs
- if( has_term('wordpress', 'category', $post) ) {
- // use template file single-wordpress.php
- $new_template = locate_template(array('single-free.php' ));
- }
- }
- return ('' != $new_template) ? $new_template : $template;
- }
上面的代码会使“免费资源”分类的文章使用指定模板文件single-free.php,重复上述步骤就可以让分类文章使用不同的自定义模板了。
原文:http://www.trickspanda.com/2014/08/use-custom-template-posts-based-categories-wordpress