0

I am using WordPress' Theme Customizer where I would like to add an option for the user to select the page template used.

Here is the code to get the page templates. This is the section that needs fixing. I borrowed this first block of code that gets the slugs of a category. Now I need to modify it to load page template as a menu option.

function get_page_templates_select() {
 $teh_cats = get_page_templates();
    $results;
    $count = count($teh_cats);
    for ($i=0; $i < $count; $i++) {
      if (isset($teh_cats[$i]))
        $results[$teh_cats[$i]->slug] = $teh_cats[$i]->name;
      else
        $count++;
    }
  return $results;
}

Here I add the control to the Theme Customizer:

    $wp_customize->add_setting( 'home_page_template_select' , array(
        'default'           => 'test',
        'type'              => 'option',
        'transport'         => 'refresh',
    ));
    $wp_customize->add_control(
        new WP_Customize_Control(
            $wp_customize,
            'home_page_template_select',
            array(
                'label'          => __( 'Home page template:', 'blankwptheme' ),
                'section'        => 'prowordpress_content_customizations',
                'settings'       => 'home_page_template_select',
                'type'           => 'select',
                'choices'        => get_page_templates_select(),
            )
        )
    );

When I run this code, the Theme Customizer times out. How can I modify the get_page_templates_select function to load properly into the control (select menu)?

EDIT:

Here is the new function I am playing around with:

function get_page_templates_select() {
 $teh_cats = get_page_templates();
 foreach ( $teh_cats as $template_name => $template_filename ) {
     $results[] = $template_name;
   }
   return $results;
}
  • 1
    templates are keyed by name and don't have a slug or name, you're loop never terminates. see the codex page for get_page_templates for an example of what is returned by that function. – Milo Apr 28 '16 at 22:35
  • Thanks for the input. So it comes down to this line right? $results[$teh_cats[$i]->slug] = $teh_cats[$i]->name; Do you mind showing me what to modify to make it work? Thank you again – cpcdev Apr 28 '16 at 23:44
0

Reading the documentation:

List of choices for 'radio' or 'select' type controls, where values are the keys, and labels are the values.

And again for get_page_templates():

Return value: (array) Where key is the name of the template and value is the filename.

Thus we can conclude:

'choices' => array_flip( get_page_templates() ),

Now I'm spoiling you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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