基于WordPress类别的模板

时间:2017-10-09 05:25:37

标签: php wordpress

我有一项任务是创建一个特定于该类别的模板。所以让我们说我有10个类别,但我想创建一个特定的模板,让我们说3个。因此,如果类别是a,b或c,我将应用某个模板。

然后当我创建帖子并将其附加到特定类别时,我需要显示与该类别相关联的特定模板。

任何标题?

5 个答案:

答案 0 :(得分:0)

高级自定义字段https://www.advancedcustomfields.com/插件应该允许您根据类别显示不同的模板。它有一些非常奇特的功能,但不记得它是否可以做到这一点。

有免费版本,请试一试。让我知道你怎么走;)

答案 1 :(得分:0)

  1. 删除single.php中的所有内容
  2. 插入“切换”代码(见下文)
  3. 使用唯一名称创建3(3)个新模板。如:single-a,single-b,single-c。
  4. 在服务器上,修改后的single.php中的神奇仙尘将在请求页面时自动加载正确的模板
  5. 请尝试以下代码。

    if (in_category('21')) {include (TEMPLATEPATH . '/single-a.php');
    }
    else if (in_category('22')) {include (TEMPLATEPATH . '/single-b.php');
    }
    else if (in_category('23')) {include (TEMPLATEPATH . '/single-c.php');
    }
    else { include (TEMPLATEPATH . '/single-29.php');
    }
    

    单a,单b,单c是3个模板,用于不同的类别和主要代码。

答案 2 :(得分:0)

如果您参考Category_Templates

Wordpress将按以下格式自动检索类别文件:

category-slug.phpcategory-ID.php

假设您有3个类别,类别a 类别b 类别c ,您可以轻松地分配每个模板创建 category-a.php category-b.php category-c.php ,并将您的愿望模板放在文件中,Wordpress将处理剩下的事情。

答案 3 :(得分:0)

您可以在这里使用category_template

function wp_category_template( $template ) {
    $cat = get_queried_object(); // get category object
    if( 1 ) // check condition 
        $template = locate_template( 'template.php' ); // load template
    return $template;
}
add_filter( 'category_template', 'wp_category_template' );

或@shashi建议你可以使用插件enter image description here

答案 4 :(得分:0)

您有3个选项:

选项1:您可以创建3个模板并根据WordPress Template Hierarchy命名,如下所示:

  • 类别-1.PHP
  • 类别-2.PHP
  • 类别-3.php

选项2:在函数文件中使用PHP代码为3个不同的类别加载1个模板:

add_filter( 'template_include', 'custom_category_template', 99 );

function custom_category_template( $template ) {

    if ( is_category(array( 1,2,3 )  )  ) {
        $new_template = locate_template( array( 'custom.php' ) );
        if ( '' != $new_template ) {
            return $new_template;
        }
    }

    return $template;
}

根据您是要为特定类别的帖子加载模板还是仅为类别存档页面加载模板,请使用in_category or is_category conditional tag

选项3 :您可以将选项2中的代码与category_template filter一起使用:

add_filter( 'category_template', 'custom_category_template' );
function custom_category_template( $template ) {

      if ( is_category(array( 1,2,3 )  )  ) {

    $template = locate_template( 'custom.php' ); 
    }
    return $template;
}

假设您的类别i.d为1,2和3.将这些类别与您的安装相匹配category i.d's

相关问题