0

I have 4 Page Templates that my theme uses for all the pages - Default Template, Template One, Template Two and Template Three.

When the relevant Page Template is selected, it loads an Advanced Custom Fields Group which enables the user to build/design a specific page - i.e. Template Two is for an F.A.Q page, Template Three is for a photo gallery.

I have added 4 new links in the Admin Sidebar which directs the user to the "Add New Page" URL - "post-new.php?post_type=page". For each link, it appends the name of the template at the end of the URL i.e. "post-new.php?post_type=page&template=three".

I would like to have the Edit Page load the correct Page Template depending on the template dictated in the URL - "template=three" would load "Template Three".

I am able to do a check with the URL and form an if statement with the below code --

list($uri, $templateURL) = explode('&', $_SERVER['REQUEST_URI']);
    if ( $templateURL == "template=services" ) {    ...

I am struggling with how to hook this into functions.php. I have tried editing the below ( https://wordpress.stackexchange.com/a/231503/182411 ) but it isn't working:

function wpse196289_default_page_template() {
  global $post;
  list($uri, $templateURL) = explode('&', $_SERVER['REQUEST_URI']);
    if ( 'page' == $post->post_type )
    && ( $templateURL == "template=services" )
    {
      $post->page_template = "page-mytemplate.php";
    }
}
add_action('add_meta_boxes', 'wpse196289_default_page_template', 1); 

1 Answer 1

0

The first issue I can see is you're missing a wrapping set of parentheses on your if statement:

your code: 

if ( 'page' == $post->post_type )
&& ( $templateURL == "template=services" )
{...

should be:

if ( 'page' == $post->post_type && $templateURL == "template=services" )
{...

I don't know for sure if that will fix your problems but it's a definite problem.

Is there a specific reason you want these to be pages and not custom post types? If you were to create three custom post types, you'd be able to use the templates as singles for your posts, which would apply your styling and ACF fields. It's a less hack-y solution as well.

1
  • You're right - my reasoning was because I wanted all content to be under one admin menu item, i.e. "Pages", and it appeared that each Custom Post Type could only be listed under it's own separate admin menu item. However, by using 'add_menu_page' and 'WP_List_Table' I have managed to collate my three Custom Post Types under a new custom admin menu item. Thanks for pointing me in the right direction!
    – JimDon
    Commented Oct 19, 2020 at 22:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.