How to Override Page Template if URL matches query?


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 ( ) 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); 
JimDon 3 months 0 Answers 10 views 0

Leave an answer