Custom template not working for existing pages

I was playing around with using a custom template per page. (Because I need to load different post types per page).

When creating a new page, and link my custom template to it via Page Attributes, it all works. I see on that new page the specific template applied.

Now, when selecting my specific the template on an existing page (= my production pages), it doesn't work... It just shows the content of the index.php.

I've been searching hours on this... Clearing cache etc doesn't help. Also no luck with deleting page and recreating. (Site is hosted on SiteGround)

EDIT: When adding a parent (in the page attribute box) to my page, the correct tempalte gets loaded... But why not on my root page?

EDIT2: Also my Woocommerce 'shop' page is not loading anymore, seems related, it is using index.php instead of the template of Woocommerce itself.

EDIT3: I found this: WP is not using the select custom template.php that its selected for a page - I also indeed use custom post types with the same name as my page, that is probably the problem. But why do I have the same problem for a page 'shop', used by WooCommerce, that still uses the index.php template? I don't have a custom post type 'shop'...

Topic page-attributes templates customization Wordpress

Category Web


as a solution, you can fully automate the selection of a template for a group of pages using slug names:

add_filter('request', function( $vars ) {

    $slug =  explode('/', explode('?', $_SERVER['REQUEST_URI'])[0]);

    array_pop ($slug);

    $temp_base = "...first_part_template_name...";
    $temp_slug = array_pop ($slug);

    if (file_exists(get_template_directory().'/'.$template.'-'.$temp_cat.'.php')) {
        get_template_part( $temp_base, $temp_slug );
    } 
}

About

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