0

I've seen several similar topics on this forum but still unable to come to a solution.

I have a parent slug named "en". I named its template as "page-en.php". Every time when I make a child page having "en" as the parent, I want to apply the description on "page-en.php" to it. There are many children.

I've been successful when it's only www.SITE.com/en/ but when there is a child it's not working out (e.g. www.SITE.com/en/child), and instead showing a reflection from "page.php", which is not desired.

Here are what I want to avoid:

*Using translation plug-ins
*Differentiating with id as it's pain to have separate templates for each id

These are "page" and not "post".

Any insight is deeply appreciated.

Hiro

0

You can override the hierarchy and load a specific page template via the page_template filter.

The fastest way is to identify the parent page by ID:

function wpd_page_template_filter( $template ){
    $page = get_queried_object();
    if( 42 == $page->post_parent ){ // en page has ID of 42
        $template = locate_template( 'page-en.php' );
    }
    return $template;
}
add_filter( 'page_template', 'wpd_page_template_filter' );

or you can also identify it by slug with an extra step:

function wpd_page_template_filter( $template ){
    $page = get_queried_object();
    $parent_slug = get_post_field( 'post_name', $page->post_parent );
    if( 'en' == $parent_slug ){
        $template = locate_template( 'page-en.php' );
    }
    return $template;
}
add_filter( 'page_template', 'wpd_page_template_filter' );

If your page is a grandchild or lower, you can get the topmost parent with the get_ancestors function

  • It worked, thank you so much!! I've been asking all over without a success, but finally I did it! Really appreciate it. – Sushimaru Mar 3 at 7:49

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.