Reordering a drag-and-drop list in WordPress

by Steph on October 12, 2009

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' );
DiggTwitterFacebookLinkedIn

{ 1 comment… read it below or add one }

John Crumpton May 25, 2010 at 9:15 am

Thank you for sharing – very handy!

Reply

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Previous post:

Next post: