wordpress functions.php - 为每个帖子类别使用不同的页面模板

时间:2016-07-15 01:16:54

标签: php wordpress function templates categories

我想挂钩到save_post函数,找出帖子所属的类别,然后为每个类别中的帖子分配不同的页面模板。我已经尝试了大约30个不同版本,没有运气。有人请帮我指出正确的方向吗?

add_action( 'save_post', 'assign_custom_template' );
function assign_custom_template($post_id) {
    $category = get_the_category($post_id);
    $cat_id = $category->cat_ID;
    if( $cat_id == 1 ) {
        update_post_meta($post_id, "_wp_page_template", "template1.php");
    }
    if( $cat_id == 2 ) {
        update_post_meta($post_id, "_wp_page_template", "template2.php");
    }
}

2 个答案:

答案 0 :(得分:2)

您只需要创建category-1.php,其呈现为template1.phpcategory-2.php在主题根目录中呈现为template2.php

有关详细信息,请参阅template hierarchy

答案 1 :(得分:0)

我试图在我的帖子中模仿正式的WP层次结构方案&自定义帖子类型,但它没有发生。我最终使用自定义帖子类型,以便我可以为“列表”页面和“个人”页面分配模板。然后我写了一些javascript来查找URL中的post-type字符串,如果检测到它,它会将current_page_parent / ancestor类添加到相应的菜单项中。不完美或完全面向未来,但它完成了工作。

如果有人想出更好的解决方案,请发布!