Categories
WordPress

Reordering a drag-and-drop list in WordPress

This took me far too long to figure out, so thought it might save someone else some time.

Include CSS and jQuery:
<link type="text/css" href="/includes/jquery/css/ui-lightness/jquery-ui-1.7.2.custom.css" rel="Stylesheet" />

The HTML:
<ul id="new_fields">
   <li id="field_id_44" class="ui-state-default">Item 1</li>
   <li id="field_id_5" class="ui-state-default">Item 2</li>
   <li id="field_id_9" class="ui-state-default">Item 3</li>
</ul>

The Javascript:

jQuery(document).ready(function(){
jQuery("#new_fields").sortable({
cursor:'move',
update:function(){
var order=jQuery('#new_fields').sortable('serialize');
jQuery.ajax({
type: "POST",
url: "<?php bloginfo( 'wpurl' ); ?>/wp-admin/admin-ajax.php",
data: "action=update_field_order&" + order
});
}});
jQuery("#new_fields").disableSelection();
});

The php function called by the AJAX:

function update_field_order(){
global $wpdb;
foreach ($_POST['field_id'] as $position => $item)
$wpdb->query("UPDATE table_name SET list_order='{$position}' where id=$item");
die();
}
add_action('wp_ajax_update_field_order', 'update_field_order' );

3 replies on “Reordering a drag-and-drop list in WordPress”

Leave a Reply to Scott Drinkwater Cancel reply

Your email address will not be published. Required fields are marked *