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

wordpress functions.php - use different page template for each post category

我想hook到save_post函数中,找出post属于哪个类别,然后为每个类别中的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");
    }
}

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

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

我试图在我的 post 和自定义 post 类型中模拟官方 WP 层次结构方案,但它并没有发生。我最终使用了自定义 Post 类型,这样我就可以将模板分配给 "list" 页面和 "individual" 页面。然后我写了一些 javascript 来寻找 URL 中的 post 类型的字符串,如果检测到它,它会将 current_page_parent/ancestor 类 添加到适当的菜单项。不完美或完全面向未来,但它完成了工作。

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