Posted on by

Let us see how we can make a better parent page selector for the edit page screen in the admin section.

When you create a new page in WordPress you have the  option for selecting a parent page from a dropdown menu – nice and simple.

parent page selector dropwdown - closed

The problem arises when you start to have dosens or hundreds of pages.parent page selector dropdown

Even with the indentation is starts to get difficult to find the page you are looking for.

The solution: select2 to the rescue

Now, it would be nice to be able search the parent page you are looking for. With select2 we can get that option. At the end it will look something like this.

 

parent page selector dropdown- select2

Code for the new  parent page selector

The implementation is fairly straight forward:

  1. Include the select2 library.
  2. Have it replace the default dropdown.

I register a stylesheet and a javascript file for the admin section in WordPress. Copy and paste the needed code from the select2 library into these files or register them independently.


/**
 * Register and enqueue in the WordPress admin.
 */
function bk_enqueue_custom_admin_style() {
        wp_register_style( 'custom_wp_admin_css', get_template_directory_uri() . '/inc/assets/css/admin.css', false, '1.0.0');
        wp_enqueue_style( 'custom_wp_admin_css' );

        wp_register_script( 'custom_wp_admin_js', get_template_directory_uri() . '/inc/assets/js/dmly-admin.js', 'jquery', '1.0.1', true );
        wp_enqueue_script( 'custom_wp_admin_js' );
}
add_action( 'admin_enqueue_scripts', 'bk_enqueue_custom_admin_style' );

The next thing is simply to call the select2 function

 


(function( $ ){
    $('#parent_id').select2();
} )( jQuery );

All in all, not too bad.

This entry was posted in Code.

Leave a Reply

Your email address will not be published. Required fields are marked *