0

I'm developing a WordPress theme with several templates. One template is called "Tabs". If a page with this template assigned has children pages, parts of their contents are shown in tabs on the parent page. Therefore I only want to allow certain templates for the children pages.

Is it possible to modify the list (dropdown) of available templates under certain conditions? Is there a hook to achieve this?

My filter/action should look like this (pseudocode):

if(parent_page->template == 'tabs')
   remove template != 'tab-content'

2 Answers 2

1

The list of available templates is generated by get_page_templates. By the end of this function you see a filter that allows you to modify the output. You can use that to change it under certain conditions like this:

add_filter ('theme_page_templates','wpse302574_conditional_templates', 10, 4);

function wpse302574_conditional_templates ($post_templates, $this, $post, $post_type) {
  $parent_id = wp_get_post_parent_id ($post->ID);
  if (get_page_template_slug ($parent_id) == 'slug_of_your_parent_template') {
    // remove unwanted templates from $post_templates
    }
  return $post_templates;
  }

( I didn't test this code, some debugging may be necessary )

0

You can do something like this

function wpdocs_filter_theme_page_templates( $page_templates, $this, $post ) {

      $parent_id = wp_get_post_parent_id( $post->ID );

      $parent_template = get_page_template_slug( $parent_id );

      if( 'template-parent.php' === $parent_template ){ // compare parent template

        foreach ($page_templates as $key => $value) {

          if( 'template-child.php' != $key ){ // compare child template

            unset( $page_templates[$key] ); // This will unset all the template except default template and child template

          }
        }

      }

      return $page_templates;
  }
  add_filter( 'theme_page_templates', 'wpdocs_filter_theme_page_templates', 20, 3 );

See https://developer.wordpress.org/reference/hooks/theme_page_templates/

Your Answer

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

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