Php 显示特定类别的自定义模板

Php 显示特定类别的自定义模板,php,wordpress,Php,Wordpress,我有一个“计划”类别,这个类别有孩子。(例如程序->提高速度) 我想为程序类别的孩子显示自定义类别模板 我发现: WordPress具有模板包含函数,该函数在WordPress包含预定模板文件之前立即执行。这可用于覆盖WordPress的默认模板行为 因此,我尝试在functions.php文件中使用以下代码: function wpse_template_check( $template ) { if ( is_category() ) { // Get categor

我有一个“计划”类别,这个类别有孩子。(例如程序->提高速度)

我想为程序类别的孩子显示自定义类别模板

我发现: WordPress具有模板包含函数,该函数在WordPress包含预定模板文件之前立即执行。这可用于覆盖WordPress的默认模板行为

因此,我尝试在functions.php文件中使用以下代码:

function wpse_template_check( $template ) {
    if ( is_category() ) {
        // Get category information
        $cat = get_query_var( 'cat' ); 
        // read the category parent 
        $parent_category = $cat->category_parent;

        //I want to load this template
        $new_template = locate_template( array( 'category-program.php' ) );

        //Program category have ID=43 so I check here if parent category = program 
        if ( ($parent_category) == 43) {
            return $new_template;
        }
    }
    return $template;
}
add_filter( 'template_include', 'wpse_template_check' );
但它不起作用…

编辑

这里的问题是,
get\u query\u var('cat')
返回当前类别ID。如果启用了调试,您将看到以下通知

注意错误:[8]尝试获取非对象的属性


您应该将
get\u query\u var('cat')
替换为
get\u queryed\u object()
,这将获取查询的对象。

不幸的是,仍然无法工作。顺便说一句,我修改了这段代码:在那里,Robert使用带有数组的locate_模板,他的代码工作正常。所以我不认为这行代码有什么问题。我很高兴。享受。:-)