代码之家  ›  专栏  ›  技术社区  ›  Matrym

使所有Wordpress类别使用它们的父类别模板

  •  13
  • Matrym  · 技术社区  · 16 年前

    我想更改默认的模板层次结构行为,并强制所有没有自己的类别模板文件的子类别级页面引用其父类别模板文件。在我的另一个岗位上, Richard M. gave an excellent answer 这解决了单个子类别的问题。有人知道如何抽象吗?

    function myTemplateSelect()
    {
        if (is_category()) {
            if (is_category(get_cat_id('projects')) || cat_is_ancestor_of(get_cat_id('projects'), get_query_var('cat'))) {
                load_template(TEMPLATEPATH . '/category-projects.php');
                exit;
            }
        }
    }
    
    add_action('template_redirect', 'myTemplateSelect');
    

    3 回复  |  直到 9 年前
        1
  •  24
  •   TheDeadMedic    10 年前
    /**
     * Iterate up current category hierarchy until a template is found.
     * 
     * @link http://stackoverflow.com/a/3120150/247223
     */ 
    function so_3119961_load_cat_parent_template( $template ) {
        if ( basename( $template ) === 'category.php' ) { // No custom template for this specific term, let's find it's parent
            $term = get_queried_object();
    
            while ( $term->parent ) {
                $term = get_category( $term->parent );
    
                if ( ! $term || is_wp_error( $term ) )
                    break; // No valid parent
    
                if ( $_template = locate_template( "category-{$term->slug}.php" ) ) {
                    // Found ya! Let's override $template and get outta here
                    $template = $_template;
                    break;
                }
            }
        }
    
        return $template;
    }
    
    add_filter( 'category_template', 'so_3119961_load_cat_parent_template' );
    

    这将向上循环父层次结构,直到找到立即模板。

        2
  •  4
  •   helgatheviking    15 年前

    我想知道如何对继承人的分类法做同样的事情。在这种情况下,HeadMedic的答案似乎也起了作用,但有一些调整:

    function load_tax_parent_template() {
        global $wp_query;
    
        if (!$wp_query->is_tax)
            return true; // saves a bit of nesting
    
        // get current category object
        $tax = $wp_query->get_queried_object();
    
        // trace back the parent hierarchy and locate a template
        while ($tax && !is_wp_error($tax)) {
            $template = STYLESHEETPATH . "/taxonomy-{$tax->slug}.php";
    
            if (file_exists($template)) {
                load_template($template);
                exit;
            }
    
            $tax = $tax->parent ? get_term($tax->parent, $tax->taxonomy) : false;
        }
    }
    add_action('template_redirect', 'load_tax_parent_template');
    
        3
  •  2
  •   Teeks    16 年前

    改用STYLESHEETPATH。例如

    $template = STYLESHEETPATH . "/category-{$cat->slug}.php";