Home / Admin / Custom drag and drop
Duplicate Snippet

Embed Snippet on Your Site

Custom drag and drop

Allows you to drag and drop to reorder posts in the WP backend.

<10
Code Preview
php
<?php
function enqueue_admin_reorder_scripts() {
    global $pagenow;
    
    // Ensure the script is not loaded on the plugins page
    if ($pagenow !== 'plugins.php') {
        wp_enqueue_script('jquery-ui-sortable');
        wp_add_inline_script('jquery-ui-sortable', '
            jQuery(document).ready(function($) {
                var $sortableList = $("#the-list");
                var postType = $("body").attr("class").match(/post-type-([^\s]+)/)[1];
                $sortableList.sortable({
                    update: function(event, ui) {
                        var postOrder = $sortableList.sortable("toArray", { attribute: "id" }).toString();
                        $.post(ajaxurl, {
                            action: "save_post_order",
                            order: postOrder,
                            postType: postType
                        }, function(response) {
                            console.log(response);
                        });
                    }
                });
            });
        ');
        wp_add_inline_style('wp-admin', '
            #the-list {
                cursor: move;
            }
        ');
    }
}
add_action('admin_enqueue_scripts', 'enqueue_admin_reorder_scripts');
function save_post_order() {
    if (isset($_POST['order']) && isset($_POST['postType'])) {
        global $wpdb;
        $postOrder = explode(',', $_POST['order']);
        $postType = sanitize_text_field($_POST['postType']);
        
        foreach ($postOrder as $menuOrder => $postId) {
            $postId = intval(str_replace('post-', '', $postId));
            $wpdb->update($wpdb->posts, array('menu_order' => $menuOrder), array('ID' => $postId, 'post_type' => $postType));
        }
        wp_send_json_success(array('message' => 'Post order updated successfully', 'order' => $_POST['order'], 'postType' => $_POST['postType']));
    } else {
        wp_send_json_error(array('message' => 'Invalid parameters'));
    }
}
add_action('wp_ajax_save_post_order', 'save_post_order');
function set_custom_post_order($query) {
    if (!is_admin() || !$query->is_main_query()) {
        return;
    }
    
    if ($query->get('orderby') == '') {
        $query->set('orderby', 'menu_order');
        $query->set('order', 'ASC');
    }
}
add_action('pre_get_posts', 'set_custom_post_order');

Comments

Add a Comment