wordpress functions.php-为每个帖子类别使用不同的页面模板 [英] wordpress functions.php - use different page template for each post category
问题描述
我想加入save_post函数,找出帖子所在的类别,然后为每个类别中的帖子分配不同的页面模板。我尝试过大约30种不同的版本,但都没有碰到运气。有人可以帮我指出正确的方向吗?
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");
}
}
推荐答案
I试图在我的帖子中模仿官方WP层次结构方案;自定义帖子类型,但这只是没有发生。我最终使用了自定义帖子类型,以便可以将模板分配给列表页面和个人页面。然后,我写了一些JavaScript,在URL中查找后置类型的字符串,如果检测到,则会将current_page_parent / ancestor类添加到适当的菜单项中。
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!
这篇关于wordpress functions.php-为每个帖子类别使用不同的页面模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!