Custom page template for multiple pages

admin2025-05-31  0

A site I'm currently working on has a page structure like this

About Us
|
|_People
| |
|  _ Person 1
|  _ Person 2
|  _ Person 3
|... etc ...

Every 'Person' page is a separate page, but they all have the same structure using a few ACF fields to display a person's bio, photo etc.

I know how to create a custom page template for one specific page, i.e. page-slug.php, but I want to use one page template for all of those subpages.

What would be the easiest way to accomplish this?

A site I'm currently working on has a page structure like this

About Us
|
|_People
| |
|  _ Person 1
|  _ Person 2
|  _ Person 3
|... etc ...

Every 'Person' page is a separate page, but they all have the same structure using a few ACF fields to display a person's bio, photo etc.

I know how to create a custom page template for one specific page, i.e. page-slug.php, but I want to use one page template for all of those subpages.

What would be the easiest way to accomplish this?

Share Improve this question asked Jul 6, 2016 at 17:02 RubenRuben 1331 silver badge6 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 6

You can always make use of the page_template filter to tell WordPress to use a specific page template for all child pages of a certain parent. It is as easy as creating a special page template, lets call it page-wpse-person.php.

Now it is as easy as including that template whenever a child page of people is being viewed. For the sake of example, lets say the page ID of people is 10

add_filter( 'page_template', function ( $template ) use ( &$post )
{
    // Check if we have page which is a child of people, ID 10
    if ( 10 !== $post->post_parent )
        return $template;

    // This is a person page, child of people, try to locate our custom page
    $locate_template = locate_template( 'page-wpse-person.php' );

    // Check if our template was found, if not, bail
    if ( !$locate_template )
        return $template;

    return $locate_template;
});

The easiest way would be to create a custom post type 'person', in which you include the custom fields. The WordPress template hierarchy would then ensure that the single-person.php template is used for those posts.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748626695a313622.html

最新回复(0)