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

Deadly 提交于 2019-12-11 00:15:31

问题


I want to hook into the save_post function, find out what category the post is in, and then assign a different page template for posts in each category. I've tried about 30 different versions of this with no luck. Will someone please help point me in the right direction?

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");
    }
}

回答1:


You just need to create category-1.php which rendered as template1.php and category-2.php which rendered as template2.php in your theme root.

See template hierarchy for more info.




回答2:


I tried to emulate the official WP hierarchy scheme among my posts & custom post types, but it just wasn't happening. I ended up using Custom Post Types so that I could assign templates to both the "list" pages and the "individual" pages. And then I wrote some javascript that looks for the post-type string in the URL, and if it's detected, it adds the current_page_parent/ancestor classes to the appropriate menu items. Not perfect or totally future-proof, but it gets the job done.

If someone comes up with a better solution, please post it!



来源:https://stackoverflow.com/questions/38386487/wordpress-functions-php-use-different-page-template-for-each-post-category

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