Wp admin drag and drop

From Lonsdale201/wp-agent-skills · View interactive version

Wp admin drag and drop is an AI agent skill from the GitHub repository Lonsdale201/wp-agent-skills. Build WordPress admin drag-and-drop UI with core's bundled jQuery UI Sortable, Draggable, Droppable, optional `jquery-touch-punch`, `wp-api-fetch`, and `wp-a11y.speak()`. Covers flat reorder lists, connected lists / kanban columns, palette-to-dropzone clones, hierarchical tree indentation, REST orde

How to use this skill

Skill file

WordPress Admin Drag-and-Drop

WP ships a complete jQuery UI drag-and-drop toolkit and the WAI-ARIA helper core itself uses to announce moves. You do not need SortableJS, dnd-kit, or Dragula for an admin UI. The blocker isn't the API — it's that nobody documents which primitive matches which UX a plugin developer actually wants to build. This skill is that mapping.

When to use this skill

Trigger when ANY of the following is true:

Proof this is reusable: where core itself runs these primitives

Same three jQuery UI plugins, four wildly different UXes. If your plugin scenario looks like ANY of these, the same toolkit works for you.

| Core surface | Pattern used | What you can build with the same primitive |

|---|---|---|

| Postbox on post edit screens | Flat sortable + connected sortables (between context columns) | Repeater rows, FAQ list, rule list |

| Dashboard widgets | Same postbox engine | Plugin dashboard cards, status panels |

| Pre-Gutenberg widget admin (Appearance → Widgets) | Palette → drop zone, with cloned helper | Block library, action library, condition builder |

| Nav menus admin (Appearance → Menus) | Hierarchical sortable with depth math | Any tree UI (term reorder with nesting, page tree, file/folder tree) |

| Admin gallery in media | Flat sortable on attachment thumbs | Image carousel order, slider order |

This isn't theoretical — these are stable, production WP features, all built on the same three handles: jquery-ui-sortable, jquery-ui-draggable, jquery-ui-droppable.

What you enqueue

The handles are pre-registered in wp-includes/script-loader.php. Declare them as deps:

add_action( 'admin_enqueue_scripts', static function ( string $hook_suffix ): void {
    if ( 'settings_page_myplugin' !== $hook_suffix ) {
        return;
    }
    wp_enqueue_script(
        'myplugin-builder',
        plugins_url( 'assets/builder.js', MYPLUGIN_FILE ),
        array(
            'jquery-ui-sortable',     // pick whichever you actually need
            'jquery-ui-draggable',    // — leave the rest out
            'jquery-ui-droppable',
            'jquery-touch-punch',     // optional: touch device support
            'wp-a11y',                // for wp.a11y.speak()
            'wp-i18n',                // for wp.i18n translations in announcements
            'wp-api-fetch',           // for persisting order via REST
        ),
        MYPLUGIN_VERSION,
        array( 'in_footer' => true )
    );
} );

| Handle | Version | When you need it |

|---|---|---|

| jquery-ui-sortable | 1.14.2 in WP 7.1 | Any reorderable list |

| jquery-ui-draggable | 1.14.2 in WP 7.1 | Palette items / freely-dragged elements |

| jquery-ui-droppable | 1.14.2 in WP 7.1 | Drop targets that aren't sortable lists (trash zone, status bucket) |

| jquery-touch-punch | n/a | Touch device support for any of the above |

| wp-a11y | n/a | wp.a11y.speak() for screen reader announcements |

Decision tree

| You want… | Use |

|---|---|

| Reorder a single list of plugin items | .sortable() on the list |

| Move items between multiple lists (kanban, settings columns) | .sortable({ connectWith }) on each list |

| A library/palette of templates dragged INTO a builder area | Palette: .draggable({ connectToSortable, helper: 'clone' }). Target: .sortable() |

| A drop target that is NOT a sortable list (delete zone, "send to status X" bucket, favorites) | .droppable({ accept, drop }) |

| Hierarchical tree with parent/child indentation | .sortable() + depth-aware sort / stop handlers (see Pattern 4) |

| Anything above, on phones/tablets | Add jquery-touch-punch as a dep |

Pattern 1 — flat sortable list

The most common plugin scenario. Repeater rows in a settings page, FAQ items, rule lists, pricing tiers, anything where order matters but there's no hierarchy.

jQuery( function ( $ ) {
    $( '#myplugin-rules' ).sortable( {
        items: '> .rule-row',
        handle: '.rule-handle',
        placeholder: 'rule-placeholder',
        cursor: 'move',
        tolerance: 'pointer',
        forcePlaceholderSize: true,
        update: function () {
            const $list = $( this );
            const order = $( this ).sortable( 'toArray', { attribute: 'data-rule-id' } );
            $list.sortable( 'disable' );
            wp.apiFetch( {
                path: '/myplugin/v1/rules/order',
                method: 'POST',
                data: { order },
            } ).then( () => {
                wp.a11y.speak( wp.i18n.__( 'Order saved.', 'myplugin' ) );
            } ).catch( () => {
                wp.a11y.speak( wp.i18n.__( 'Order was not saved. Reloading.', 'myplugin' ) );
                window.location.reload(); // Restore canonical server order.
            } ).finally( () => $list.sortable( 'enable' ) );
        },
    } );
} );

Why toArray({ attribute: 'data-rule-id' }) instead of DOM id: in repeater rows cloned from a template, DOM ids tend to collide. Use data-* attributes — that's what production builders do.

For metabox-style flat lists (with collapse + Screen Options), see wp-admin-postbox-sortable — that's the special-case skill for the postbox-specific chrome.

Pattern 2 — connected lists (kanban / move between zones)

When you have multiple lists and items can move between them. Plugin use cases: kanban board for membership states, two-column "available / enabled" toggles, status-bucket UIs, multi-tier rule sets where rules can be promoted/demoted.

const $columns = $( '.builder-column' );

$columns.sortable( {
    connectWith: '.builder-column',
    items: '> .builder-card',
    handle: '.card-handle',
    placeholder: 'card-placeholder',
    forcePlaceholderSize: true,
    update: function ( event, ui ) {
        if ( ui.sender ) {
            return; // The sender list also fires update; only persist once.
        }
        const payload = {};
        $columns.each( function () {
            payload[ this.id ] = $( this ).sortable( 'toArray', { attribute: 'data-card-id' } );
        } );
        wp.apiFetch( {
            path: '/myplugin/v1/cards/order',
            method: 'POST',
            data: payload,
        } ).then( () => {
            wp.a11y.speak( wp.i18n.__( 'Board updated.', 'myplugin' ) );
        } ).catch( () => {
            wp.a11y.speak( wp.i18n.__( 'Board was not saved. Reloading.', 'myplugin' ) );
            window.location.reload();
        } );
    },
} );

The critical gotcha: a cross-list move fires update on both the sender and the receiver. Dedupe on ui.sender (truthy only on the receiving list), or you'll double-save.

Pattern 3 — palette + drop zones

When you have a fixed library of items on one side, drop zones on the other. The palette item stays put (it clones); a new item lands in the drop zone. Plugin use cases: block library, action library for a logic builder, available-tags panel, condition builder.

// Draggable owns connectToSortable; the palette remains because helper is a clone.
$paletteItems.draggable( { connectToSortable: '.dropzone', helper: 'clone' } );
$dropzones.sortable( { receive: convertCloneToPersistedItem } );

connectToSortable belongs to Draggable, and helper: 'clone' keeps the source

item. receive must persist the new item, replace the temporary clone only on

success, and remove it on failure. The complete async example is in

reference.md.

Pattern 4 — hierarchical / nested (parent + child indentation)

When you need tree behavior with depth indentation that updates while dragging. Plugin use cases: hierarchical taxonomy term reorder with nesting, page-tree style site map, file/folder tree, parent/child rule grouping.

The algorithm:

[0, MAX_DEPTH], but also to the structural limit: at most one level deeper

than the previous visible row. Account for the dragged subtree so no child

exceeds MAX_DEPTH.

When persisting: walk the DOM in order, each item's parent is "the previous item with depth = current depth − 1". Server side this collapses to a flat list with parent_id per row.

See reference.md for a compact implementation. For a battle-tested implementation, read wp-admin/js/nav-menu.js:885; it includes RTL handling, accessibility hooks, and menu-specific bits most plugins don't need.

Pattern 5 — droppable trash / status bucket

When the target isn't a sortable list — a delete zone, a "send to archive" bucket, a star/favorite area, a "test now" tray.

$( '#trash-zone' ).droppable( {
    accept: '.tree-item, .rule, .placed-item',
    activeClass: 'trash-zone-active',  // while ANY draggable is being dragged
    hoverClass:  'trash-zone-hover',   // while a valid item is over us
    tolerance: 'pointer',
    drop: function ( event, ui ) {
        const id = ui.draggable.data( 'item-id' );
        ui.draggable.addClass( 'is-pending' ).attr( 'aria-disabled', 'true' );
        wp.apiFetch( {
            path: `/myplugin/v1/items/${ id }`,
            method: 'DELETE',
        } ).then( () => {
            ui.draggable.fadeOut( 150, () => ui.draggable.remove() );
            wp.a11y.speak( wp.i18n.__( 'Item deleted.', 'myplugin' ) );
        } ).catch( () => {
            ui.draggable.removeClass( 'is-pending' ).removeAttr( 'aria-disabled' );
            wp.a11y.speak( wp.i18n.__( 'Item could not be deleted.', 'myplugin' ) );
        } );
    },
} );

Useful even when you don't need a "trash" — same pattern works for "click-drag a campaign onto a date in a mini-calendar", "drag a user onto a role bucket", "drop a product onto a category preview". Any target that isn't itself a sortable list.

Persisting order — REST, not admin-ajax

Don't reach for admin-ajax.php for new endpoints. Use REST with a real

permission_callback, validation plus sanitization (order as a positive

integer array), and wp-api-fetch on the client. Server-side, verify that the

submitted IDs are the complete allowed set for that user/container: an args

schema cannot detect omitted, foreign, or duplicate business objects.

wp-api-fetch attaches X-WP-Nonce for the standard cookie-authenticated

WordPress setup when its nonce middleware is configured by core.

Accessibility — match the postbox keyboard pattern

Pointer-only drag is a WCAG fail. The pattern WP itself ships: a pair of "move up / move down" buttons per item alongside the drag handle, with wp.a11y.speak() announcements. Match it.

Use real buttons, not only a draggable handle. The click handler moves the row in the DOM, calls the same persistence routine as drag-drop, and announces with wp.a11y.speak(). See reference.md for the snippet and postbox.handleOrder() in wp-admin/js/postbox.js:98 for core's pattern.

Touch support

jQuery UI's drag handlers remain mouse-oriented. For touch devices, add jquery-touch-punch as a dep — it patches jQuery UI mouse interactions to also accept touch events. It's registered in core, so declaring it as a dep is enough. Test real touch and keyboard behavior: the old patch is compatibility support, not a modern pointer-events accessibility layer.

WordPress 7.1 updates the bundled jQuery UI components from 1.13.3 to 1.14.2

and sets jQuery.uiBackCompat = true before jquery-ui-core. The documented

widget APIs used in this skill remain available, but plugin code that reaches

into underscored widget methods, copied internals, DOM-generated class details,

or deprecated $.ui.plugin behavior must be regression-tested. Core's

back-compat flag is not a promise that private internals are stable.

Critical rules

Complex pointer/touch interactions or React-rendered surfaces may justify a

maintained external library; account for its bundle, accessibility, and

lifecycle costs explicitly.

Common AI mistakes

See reference.md for before/after snippets: flat sortable used for trees, connectToSortable placed on the wrong primitive, persisting on change, missing wp.a11y.speak(), and adding new admin-ajax handlers instead of REST routes.

Cross-references

What this skill does NOT cover

Where to look in core for proof / reference

You don't need to read these to use the patterns above — they're listed for when you want a battle-tested implementation to copy from.

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.