Getting jQuery sortable items in custom metabox

It’s a matter of wrapping the jQuery into document.ready, add a handler to the items and configure the sortable:

add_action( 'add_meta_boxes', 'metabox_wpse_66122' );

function metabox_wpse_66122() 
{
    add_meta_box(
        'my_sortable',
        __( 'My Sortable' ),
        'sortable_wpse_66122',
        'post'
    );
}

function sortable_wpse_66122() 
{
    echo '<ul class="sortable  ui-sortable">';
    $posts = get_posts( array(
       'post_type'   => 'post',
       'post_status' => 'publish',
       'posts_per_page' => 5
    ));
    foreach( $posts as $p )
       echo "<li><code class="hndle"> -[]- </code> {$p->post_title}</li>";
    echo '</ul>';
    ?>
        <script type="text/javascript">
        jQuery(document).ready(function($) 
        {    
            $( '.sortable' ).sortable({
                opacity: 0.6,
                revert: true,
                cursor: 'move',
                handle: '.hndle',
                placeholder: {
                    element: function(currentItem) {
                        return $("<li style="background:#E7E8AD">&nbsp;</li>")[0];
                    },
                    update: function(container, p) {
                        return;
                    }
                }
            });
            $( '.sortable' ).disableSelection();
        });
        </script>
    <?php
}

Leave a Comment