Drag and Drop List in WordPress

Drag and drop list in WordPress is one of the features that you may need when you develop your own widget or plugin. For example, with sortable items, you can choose the priority of list items.

How to Create a Drag and Drop List in WordPress?

Creating a draggable list in WordPress is easy because it uses jQuery to accomplish that. List to be sortable we have to use the jQuery UI file.

To start, add the below code in your themes functions.php file or if you are developing a plugin, then add it to your plugin file.

function hs_enqueue_scripts()
add_action('admin_enqueue_scripts', 'hs_enqueue_scripts');

If you want to use the sortable list on the admin page, use the above code. If you want to use the list in the front-end, then change the action hook name.

add_action('wp_enqueue_scripts', 'hs_enqueue_scripts');

This code adds jQuery UI Core to your page. Usually, it has been added, to be sure we have to add ourselves.

Create a Sortable List in WordPress

After adding the file, create your drag and drop list in your page like following code.

<ul class="ui-sortable">
    <li class="ui-sortable-handle">Item One</li>
    <li class="ui-sortable-handle">Item Two</li>
    <li class="ui-sortable-handle">Item Three</li>

As you see, there is a class in <ul> tag, named ui-sortable and ui-sortable-handle in <li> tag. These classes defined in jQuery UI to handle the sortable list.

Create a Sortable Table

There is no difference between List and Table to define as sortable. In the <table> tag, we add the classes in <tbody> tag and <tr> tags like the following code.

    <tbody class="ui-sortable">
        <tr class="ui-sortable-handle">
            <td>Item One</td>
        <tr class="ui-sortable-handle">
            <td>Item Two</td>
        <tr class="ui-sortable-handle">
            <td>Item Three</td>

As you see, the classes added to <tbody> tag and <tr> tags.

Create Drag and Drop Div in WordPress with JQuery

This is like other, but just create by <div> tag.

<div class="ui-sortable">
    <div class="ui-sortable-handle">Item One</div>
    <div class="ui-sortable-handle">Item Two</div>
    <div class="ui-sortable-handle">Item Three</div>

Final Word

With these two classes, you can create a sortable and draggable list or items where ever you want. You need just add jQuery and jQuery UI files to your page and make the sortable list with <ul> tag, <table> or <div> or what tag you want.