使 *ALL* Wordpress 类别使用其父类别模板 [英] Make *ALL* Wordpress Categories use their Parent Category Template

查看:25
本文介绍了使 *ALL* Wordpress 类别使用其父类别模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改默认模板层次结构行为,并强制所有没有自己的类别模板文件的子类别级别页面引用其父类别模板文件.在我的另一篇文章中,Richard M. 给出了一个很好的答案这解决了单个子类别的问题.有谁知道如何抽象它?

I want to change the default template hierarchy behavior, and force all subcategory level pages that don't have their own category template file to refer to their parent category template file. In my other post, Richard M. gave an excellent answer that solved the problem for an individual subcategory. Does anyone know how to abstract it?

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');

提前致谢.

推荐答案

/**
 * 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' );

这会循环父层次结构,直到找到直接模板.

This loops up the parent hierarchy until an immediate template is found.

这篇关于使 *ALL* Wordpress 类别使用其父类别模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆