supernaut
supernaut

Reputation: 311

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

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

Upvotes: 2

Views: 1150

Answers (2)

supernaut
supernaut

Reputation: 311

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!

Upvotes: 0

Minh Tri
Minh Tri

Reputation: 2471

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.

Upvotes: 2

Related Questions