0

I am building a custom theme which has an insane amount of templates. I have created an options page to allow the user to enable the page templates they wish to use. The plan is to then create a function to loop through the templates and add the ones they have enabled. I use the following function when creating a plugin but this is not being used in a plugin. I need something like the code below to work within the functions.php document.

add_filter( 'page_template', 'template_selection' );
function template_selection( $page_templates ){
    $templates = get_option('templates');
    if(in_array('1',$templates)){$page_template[] = dirname( __FILE__ ) . '/template1.php';}
    if(in_array('2',$templates)){$page_template[] = dirname( __FILE__ ) . '/template2.php';}
    return $page_templates;
}

The issue here is that the filter is not working. Any help with this matter is greatly appreciated.

6
  • I'm not sure what you mean by "enable". The page_template filter runs when the page template is loaded for a page request.
    – Milo
    Commented Dec 30, 2016 at 3:17
  • The function above does nothing. I have even added a echo 'test'; inside the function it does nothing. The function is not firing on the pages.
    – James
    Commented Dec 30, 2016 at 3:22
  • 1
    It works for me when I copy/paste your code into 2016 theme functions.php. I get two in_array errors from $templates being false instead of an array. It seems your problem is elsewhere.
    – Milo
    Commented Dec 30, 2016 at 3:29
  • I pasted the following code at the top of my functions.php document and it does nothing. add_filter( 'page_template', 'template_selection' ); function template_selection( $page_templates ){ return dirname( FILE ) . 'inc/page-templates/full-width.php'; }
    – James
    Commented Dec 30, 2016 at 3:44
  • my functions document is completely empty except this function and I get nothing.
    – James
    Commented Dec 30, 2016 at 3:47

1 Answer 1

0

After some digging I found a better function which allows you to directly modify the template listing

function page_templates( $templates ) {
    $templates['temp/template1.php'] = 'Full Width Template';
    return $templates;
}
add_filter( 'theme_page_templates', 'page_templates' );

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.