Skip to content

Instantly share code, notes, and snippets.

@EdenK
Last active August 2, 2023 13:30
Show Gist options
  • Save EdenK/20df0d549086626e1627434c3bbe4c2b to your computer and use it in GitHub Desktop.
Save EdenK/20df0d549086626e1627434c3bbe4c2b to your computer and use it in GitHub Desktop.
Wordpress: Auto set page template for child pages to be the same as parent.
<?php
/**
* Wordpress: Auto set page template for child pages to be the same as parent.
*/
function set_child_page_template( $post_id, $post, $update ) {
// Check for post type page
if( $post->post_type === 'page' ) {
// Check if its a child page
if( $post->post_parent !== 0 ) {
// If its child get the post parent template
$parent_template = get_post_meta( $post->post_parent, '_wp_page_template', true );
update_post_meta( $post_id, '_wp_page_template', $parent_template );
} else {
// If its parent update all his childs
$parent_template = get_post_meta( $post_id, '_wp_page_template', true );
$children = get_pages( ['child_of'=>$post_id] );
foreach( $children as $child ) {
update_post_meta( $child->ID, '_wp_page_template', $parent_template );
}
}
}
}
add_action('save_post', 'set_child_page_template', 10, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment