Automatically select a template for a child page with the same name as another

In a wordpress website I have this page structure:

/posts
/another-page/posts

Basically they are two different pages listing different posts, even though the name (posts) is the same. The two pages should use different templates. For the first “posts” page I just create a file called page-posts.php, and it’s automatically chosen. How can make the same thing for the other “posts” page?

Read More

Is the only solution to create a template and manually select it from the dropdown in the admin page? Isn’t there any way to change the slug withouth affecting the url?

Related posts

Leave a Reply

2 comments

  1. You can create two template files name page-{id}.php for each page. This would handle both pages for you.

    Template Hierarchy Page Section

    The IDs for each page will be unique. So when you select Edit from the WP-Admin area, look at the URL and you can find the ID.

    /wp-admin/post.php?post=6163&action=edit
    

    For this page, my page ID would 6163. So the template name would page-6163.php.

    Cheers

  2. You could try hooking to the page template action, checking for your custom url structure, and if it exists, outputting your custom template.

     add_filter( 'page_template', 'custom_page_template' );
    
     function custom_page_template( $page_template )  {
         $url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
    
         if ( false !== strpos( $url, '/another-page/posts' ) ) {
             $page_template = dirname(  __FILE__  ) . '/path_to_my_template.php';
         }
    
         return $page_template;
     }