WordPress.org

Ready to get started?Download WordPress

Forums

Children template (3 posts)

  1. bryan868
    Member
    Posted 3 years ago #

    Looking for a way to auto-apply a template to all of a page's children. Basically I don't want to go in and assign a custom template for all the children pages.

    Currently... we can create "page-slug.php" or "page-id.php" to apply a template to a page automatically. How can I do... "page-slug-children.php" or "page-id-children.php" to auto-apply the template to all children?

    Any ideas?

  2. esmi
    Forum Moderator
    Posted 3 years ago #

    I believe this was just answered on the wp-hackers list but, for the record:

    function apply_my_template( $postID, $post ) {
        if (
            !current_user_can( 'edit_post', $postID )
            || 'page' != $post->post_type
            || wp_is_post_revision( $postID )
            || wp_is_post_autosave( $postID )
            || 'auto-draft' == $post->post_status
            || 'trash' == $post->post_status
            )
            return $postID;
        if ( 49 == $post->post_parent )
            update_post_meta( $postID, '_wp_page_template',
    'page-my-template.php' );
    
    }
    add_action( 'save_post', 'apply_my_template', 10, 2 );
  3. biralucena
    Member
    Posted 3 years ago #

    Mixing some functions from here and here I wrote the code below in my functions.php:

    function the_slug($pageID) { // Is there any other way to get the parent page slug?
    
    	$post_data = get_post($pageID, ARRAY_A);
    	$slug = $post_data['post_name'];
    	return $slug;
    }
    
    function child_page_template(){
    	global $post;
    	$parent_page_slug = the_slug($post->post_parent);
    	$page_template = 'page-'. $parent_page_slug . '-child.php'; //name it on your own
    	$parents = get_post_ancestors($post->ID); // if is child
    	if($parents){update_post_meta($post->ID,'_wp_page_template',$page_template);}
    
    }
    
    add_action('save_post','child_page_template');

    Now, every time a child page is created or updated it will have as page template a file named "page-parentslug-child.php.

    for example:
    'PARENT' => page-slug.php (default)
    'parent'> 'CHILD' => page-'PARENTSLUG'-child.php
    'parent'> 'child'> 'GRANDCHILD' => page-'CHILDSLUG'-child.php
    'parent'> 'child'> 'grandchild' > 'GRAND-GRANDCHILD' => page-'GRANDCHILDSLUG'-child.php (...) and so on.

    That it

Topic Closed

This topic has been closed to new replies.

About this Topic