Drag and Drop List in WordPress

Drag and Drop List in WordPress

Drag and drop list in WordPress CMS is one of the features that you may need when you develop your own custom 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()
{
    wp_enqueue_script('jquery-ui-core');
}
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 or website. Usually, it has been added, but to be sure we have to add it ourselves.

Create a Sortable List in WordPress

After adding the file, create your drag-and-drop list on your page like the 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>
</ul>

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

Create a Sortable Table

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

<table>
    <tbody class="ui-sortable">
        <tr>
            <th>Number</th>
            <th>Item</th>
        </tr>
        <tr class="ui-sortable-handle">
            <td>1</td>
            <td>Item One</td>
        </tr>
        <tr class="ui-sortable-handle">
            <td>2</td>
            <td>Item Two</td>
        </tr>
        <tr class="ui-sortable-handle">
            <td>3</td>
            <td>Item Three</td>
        </tr>
    </tbody>
</table>

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

Create Drag and Drop Div tag in WordPress with JQuery

This is like others, 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>
</div>

Final Word

With these two classes, you can create a sortable and draggable list of 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.