Dynamically assign same page template to child page as parent olatechproMarch 29, 20236 Views How to assign parent page template to its child pages dynamically? Post Views: 6 Related postsGet rid of this Strict Standards warningWooCommerce: get_current_screen not working with multi languageCan’t login on WordPressForce HTTPS using .htaccess – stuck in redirect loopWordPress: Ajax not working to insert, query and result dataHow Can I pass an image file to wp_handle_upload?
Paste following code to your theme’s functions.php: add_action('save_post','changeTemplateOnSave'); function changeTemplateOnSave(){ global $post; $curr_tmp = get_post_meta($post->ID, '_wp_page_template', true); $parent_tmp = get_post_meta($post->post_parent, '_wp_page_template', true); if($post->post_parent) update_post_meta($post->ID,'_wp_page_template',$parent_tmp,$curr_tmp); } This will force WordPress to change page template to it’s parent template on post save. Not tested but should work. Log in to Reply
A little correction to the Max Yudin’s solution: add_action('save_post','changeTemplateOnSave'); function changeTemplateOnSave(){ global $post; $curr_tmp = get_post_meta($post->ID, '_wp_page_template', true); if($post->post_parent){ $parent_tmp = get_post_meta($post->post_parent, '_wp_page_template', true); update_post_meta($post->ID,'_wp_page_template',$parent_tmp,$curr_tmp); } } Log in to Reply
One further little correction if you care about php warnings in the background. When creating a new post/page the folllow notice was being output Notice: Trying to get property of non-object error Fixed this by making sure $post exists or and is not empty. add_action('save_post','changeTemplateOnSave'); if ( ! function_exists( 'changeTemplateOnSave' ) ) { function changeTemplateOnSave() { global $post; if ($post) { $curr_tmp = get_post_meta( $post->ID, '_wp_page_template', true ); if ( $post->post_parent ) { $parent_tmp = get_post_meta( $post->post_parent, '_wp_page_template', true ); update_post_meta( $post->ID, '_wp_page_template', $parent_tmp, $curr_tmp ); } } } } Log in to Reply
Paste following code to your theme’s
functions.php
:This will force WordPress to change page template to it’s parent template on post save.
Not tested but should work.
A little correction to the Max Yudin’s solution:
One further little correction if you care about php warnings in the background.
When creating a new post/page the folllow notice was being output
Notice: Trying to get property of non-object error
Fixed this by making sure $post exists or and is not empty.