【问题标题】:Wordpress Template for all child categories but not for parent适用于所有子类别但不适用于父类别的 Wordpress 模板
【发布时间】:2013-03-14 18:25:19
【问题描述】:

我在 Wordpress 中找到的对子类别和孙子类别使用相同类别模板的最佳方法就在 stackoverflow 上: https://stackoverflow.com/a/3117202/391929

但是如何让 JUST 子类别使用该模板而不是基本父类别?

我尝试过像这样编辑 if 行,从这里开始:

if (is_category(get_cat_id('projects')) || cat_is_ancestor_of(get_cat_id('projects'), get_query_var('cat')))

到这里:

if (is_category(get_cat_id('projects')) || cat_is_ancestor_of(get_cat_id('projects'), get_query_var('cat')))

但它不起作用,为什么?

【问题讨论】:

    标签: wordpress templates categories


    【解决方案1】:

    我设法以程序方式解决了这个问题:

    1在主题功能中添加了这个sn-p:

    add_action('template_redirect', 'load_category_tree_template');
    function load_category_tree_template() {
            if (is_category() && !is_feed()) {
                // replace 'your-base-category-slug' with the slug of root category
                $base_tree_cat_id = get_cat_id('your-base-category-slug'); 
                    // get current category id
                $catid = get_query_var('cat'); 
    
                if (is_category($base_tree_cat_id) || cat_is_ancestor_of($base_tree_cat_id, $catid)) {
                    load_template(STYLESHEETPATH . '/category-your-base-category-slug.php');
                    exit;
                }
            }
        }
    

    然后在 category-your-root-category-slug.php 文件中,我根据当前类别 slug 包含一个不同的其他文件:

    <?php get_header(); ?>
    
    <?php
    if (is_category( )) {
      $cat = get_query_var('cat');
      $currentcat = get_category ($cat);
      $currentslug = $currentcat->slug;
     }
    // if we are in base category we know it by the slug
    if ($currentslug == 'your-base-category-slug'){
            // if we are load a file with the loop for the root category
        require_once('post-loop-caregory-tree-root.php'); 
    }else{
            // otherwise we are not in the root, so show the loop for all other category in the tree
        require_once('post-loop-category-tree.php'); 
    }
    ?>
    
    <?php get_footer(); ?>
    

    我知道它可以做得更好,但最终它是非常简单的解决方案。

    【讨论】:

    • 由于没有其他建议,我将我的答案作为好的答案,但我确信这可以以更好的方式完成......
    猜你喜欢
    • 1970-01-01
    • 2011-04-26
    • 2019-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多