Control attachments menu order with jQuery Sortable

I’ve managed create a metabox that lets me upload and then fetch the images and then also been able to add jquery ui sortable to be able to sort the images, however I’ve no idea how to add actual functionality so that the sort order get saved.

If someone has an idea how to achieve this or some tutorial that would be helpful, please share, I’m helplessly stuck here.

Read More

Thanks.

Edit:
Basically, what I need to know is how to tie jQuery sortable together with the functionality that handles the different attachments menu_order.

Related posts

Leave a Reply

3 comments

  1. To save the menu order use wp_update_post() with each attachment ID and its new menu position:

    $thisattachment = array();
    $thisattachment['ID'] = $thisid;
    $thisattachment['menu_order'] = $new_menu_position;
    wp_update_post($thisattachment);
    

    EDIT – assuming these are already attachments and you’re updating them? Otherwise you have to insert the attachments first with wp_insert_attachment

  2. Within the WordPress admin you should be able to order the attached media associated with a post/page/custom once it’s been uploaded using the Gallery Tab. This will then effect the order in which they get called from the DB.

  3. How to get post attachments

    If you’re on a single post view, you’ll have the global $post available. If you then want to have all attachments, place the following in your code:

    $attachments = array_values( get_children( array( 
         'post_parent'      => $post->post_parent
        ,'post_status'      => 'inherit'
        ,'post_type'        => 'attachment'
        ,'post_mime_type'   => 'image'
        ,'order'            => 'ASC'
        ,'orderby'          => 'menu_order ID' 
    ) ) );
    

    'menu_order ID' means that you order by 'menu_order' AND 'ID'.

    How to sort post attachments

    Note: Your attachments are object, close to normal posts. They got an 'ID', got 'menu_order' like pages, etc.

    In some special cases, ordering won’t work, so you can use a callback function, to trigger ordering by the ID:

    usort( $attachments, 'sort_cb' );
    

    Then the function to compare and sort.

    function sort( $a, $b )
    {
        if ( $a->menu_order == $b->menu_order )
            return null;
    
        return ( $a->menu_order > $b->menu_order ) ? +1 : -1;
    }