Drag and Drop Categories
November 25, 2024 ยท AI Conversations
### **1. Use a Plugin**
There are existing plugins that add drag-and-drop sorting for categories or taxonomies. Examples include:
– **Category Order and Taxonomy Terms Order**: Allows you to reorder categories and custom taxonomies using drag-and-drop.
– Install the plugin from the WordPress Plugin Repository.
– Once installed, navigate to `Categories` or the custom taxonomy page in the WordPress admin and reorder the terms.
—
### **2. Custom Code Implementation**
If you prefer to build a custom solution, you can achieve this using JavaScript and PHP.
#### **Steps:**
##### **a. Enqueue Scripts**
Enqueue jQuery UI Sortable or similar libraries to create the drag-and-drop functionality.
Add the following to your theme's `functions.php` file:
function custom_enqueue_scripts($hook) {
if ($hook === 'edit-tags.php' && isset($_GET['taxonomy']) && $_GET['taxonomy'] === 'category') {
wp_enqueue_script('jquery-ui-sortable');
wp_enqueue_script('custom-category-drag-drop', get_template_directory_uri() . '/js/category-drag-drop.js', ['jquery', 'jquery-ui-sortable'], null, true);
}
}
add_action('admin_enqueue_scripts', 'custom_enqueue_scripts');
##### **b. Add JavaScript for Drag-and-Drop**
Create a `category-drag-drop.js` file in your theme's `js` folder:
jQuery(document).ready(function ($) {
const $table = $('#the-list');
$table.sortable({
items: 'tr',
cursor: 'move',
axis: 'y',
update: function (event, ui) {
const order = $table.sortable('toArray', { attribute: 'id' });
// Send the new order via AJAX
$.post(ajaxurl, {
action: 'save_category_order',
order: order,
nonce: custom_category_order.nonce
});
}
});
});
##### **c. Save the New Order**
Handle the AJAX request to save the updated order.
Add this to `functions.php`:
function save_category_order() {
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'custom_category_order_nonce')) {
wp_send_json_error(['message' => 'Invalid nonce']);
}
if (isset($_POST['order']) && is_array($_POST['order'])) {
foreach ($_POST['order'] as $index => $term_id) {
wp_update_term((int) $term_id, 'category', ['menu_order' => $index]);
}
wp_send_json_success();
}
wp_send_json_error(['message' => 'Invalid data']);
}
add_action('wp_ajax_save_category_order', 'save_category_order');
##### **d. Generate Nonce**
Pass a nonce to the JavaScript file for security:
function custom_category_order_nonce() {
wp_localize_script('custom-category-drag-drop', 'custom_category_order', [
'nonce' => wp_create_nonce('custom_category_order_nonce'),
]);
}
add_action('admin_enqueue_scripts', 'custom_category_order_nonce');
—
### **3. Use Advanced Custom Fields or Custom Taxonomy**
If you want additional metadata or custom ordering options, combine ACF with the custom drag-and-drop functionality above.
This setup lets you manage categories efficiently while maintaining a user-friendly admin interface.