Wordpress Set A Static Page/Template For All Sub-Pages

I have a wordpress install where I want to serve a static page/template for anyone arriving at a child of a certain page, e.g.

https://example.com/products/*

Would all serve a php template from within Wordpress (or even just a static file) without changing the slug, so the following:

https://example.com/products/some-product-slug
https://example.com/products/another-product-slug

Would both serve the same file without changing/redirecting the URL.

This template would also handle 404s internally, so a slug like:

https://example.com/products/does-not-exist

Would still serve the same static template.

Is this possible to configure within wordpress?

Imagine that the page/template being redirected to is completely unrelated to a post type or hierarchy, as it is serving external resources based on the slug.

Topic php permalinks custom-post-types Wordpress

Category Web


This solve the problem for me, only need the Parent-Post-ID and the full path of the template to be used for all subpages

In functions.php I have this code:

add_filter( 'template_include', 'template_subpage', 99 );
function template_subpage( $template ) {

    global $post;
    if($post->post_parent == $selected_parent_id){ // the id of the parent

        $template = get_template_directory() . '/template-subpage.php'; // template to assign to subpages
    }
    return $template;
}

Okay so I have resolved this by combining several different wordpress functionalities:

  1. Catches the template include conditionally add_filter( 'template_include', '...' );, in my case based on a regex match of the expected URI pattern
  2. locate_template('example-template.php') to then resolve my (essentially) static template
  3. A query within my example-template.php that externally retrieves the resource
  4. This must handle 404s interally as the response will always assume the post can't be found, I am always setting the header response (before get_header in the template to 202 where the resource is found.
  5. Example; if ($resource) { @header($_SERVER['SERVER_PROTOCOL'] . ' 202 Accepted', true, 202); }

Bit convoluted, but really not too much work for what I required.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.