I am working on a template which one uses on both parent and child pages.

Suppose I have a:

template name: TEST

I need to use that template on both parent and child pages:

Parent page name -> test1 -> template name:TEST

Child page name -> test2 -> Parent page test1 -> template name: TEST

  • Automatically? Just setting the template on the child page isn't enough? – Jacob Peattie Jul 11 '18 at 6:43
  • A child theme already uses the templates that a parent offers? So from the page you should be able to choose the template whichever theme you using? – anmari Jul 11 '18 at 8:02

You can use the save_post action to do it.

I think its better than the other option to check everytime the page load because it won't effects your clients and will not run everytime the page load.

Also you need to check if its the post parent its the one that saved so you will update his childrens.

Check this:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.