Make *ALL* Wordpress Categories use their Parent Category Template

我怕爱的太早我们不能终老 提交于 2019-11-27 01:10:23

问题


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

Thanks in advance.


回答1:


/**
 * 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.




回答2:


i was wondering how to do the same thing for heirarchical taxonomies. TheDeadMedic's answer seems to work in that case too w/ a few tweaks:

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:


The TEMPLATEPATH variable might not work for child themes - looks in parent theme folder. Use STYLESHEETPATH instead. e.g.

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


来源:https://stackoverflow.com/questions/3119961/make-all-wordpress-categories-use-their-parent-category-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!