0

Im writing a plugin and need to know how to add a page template in the edit page screen from within a plugin. bbPress and Buddypress both add page templates to this drop down and I can't figure out how they do it.

Not looking for template_redirect solution, needs to work in the backend. I am already making use of template_redirect and don't need any help with it!

Any assistance would be appreciated.

1 Answer 1

0

Sincerly I don't know how Buddypress and bbPress add options to page templates dropdown, and I can be wrong, but I think the only way to do it (excluding adding files to theme folder or hacking core), is to use javascript.

Create a file containing the following, save it somewhere, I will assume it is named my-script.js and it's in a subfolder 'js' of the theme folder

jQuery(document).ready(function($) {
   if (  $('select#page_template').length ) {
     var tmpl = myscriptdata.template;
     var label = myscriptdata.template_label;
     $('select#page_template').append('<option value="' + tmpl + '">' + label + '</option>');
   }
});

Then enqueue it in post.php and post-new.php, only for pages, and passing the template you want to add:

add_action('admin_enqueue_scripts', 'add_my_scripts');

function add_my_scripts( $page ) {
  if ( $page === 'post.php' || $page === 'post-new.php' ) {
    global $typenow;
    if ( $typenow === 'page' ) {
      wp_enqueue_script('myscript', get_template_directory_uri() . '/js/my-script.js', array('jquery'), null);
      $data = array(
        'template' => "my-template", // what you want to assign to dropdown value
        'template_label' => "My Template" // what you want to assign to dropdown label
      ); 
      wp_localize_script('myscript', 'myscriptdata', $data );
    }
  }
}

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.