Fix for sort order not sticking
-
We had an identical error to that described previously whereby the sort order was seemingly changing back on return to the post listing page. This was on a site running WP version 5.2.2.
I have debugged this plugin and found two bugs. The Wpso::update_menu_order method does not work when you have two posts that both have a menu_order value of 0.
For some reason it takes an array of the existing menu orders (e.g. [0,0,1,2,3]) and re-uses these indices when applying the new sort order. So if you move the one at position 2 in the list to the top, the 0 will be unchanged. Ordering is therefore ambiguous. This could be fixed by not relying on the existing values, just use [1,2,3,4,5] instead.
The other bug which compounds this issue, is when you create a new post it’s created with a menu_order of 0, so this is how you end up with multiple posts being unsortable.
Addressing either of these bugs alone will fix the issue. Therefore, since this plugin. I’ve written a fix for my project. I could have overridden the update_menu_order hook with my own solution but then I would have had to monitor this plugin for when that method was updated or fixed in future version. I therefore chose to add my own hook on post save that adds a menu_order value one greater than the current maximum for the post type. This means that new posts go straight to the bottom of the list and re-ordering works as advertised.**note:** This won’t work as a stright copy/paste. I use my own library for hooks so I don’t have to rely on the dumb opaque strings that WordPress insists on using. The closure I’m creating here automatically removes itself as soon as it’s applied to prevent recursion. There’s some background infor here if you wanna know what’s going on here: https://dev.to/thisleenoble/preventing-free-range-wordpress-hooks-3n8a
private function patchSortOrder(){ global $wpdb; if(function_exists('wpso_activate')){ // WP_Sort_Order plugin bug fix closure::createAction(action::SAVE_POST . '_' . $this->type, function ($postID, \WP_Post $post, $update = false) use ($slide, $wpdb) { if(!$post->menu_order){ $sql = 'SELECT MAX(menu_order) FROM '.$wpdb->posts.' WHERE post_type = "'.$this->type.'" '; $max = $wpdb->get_var($sql); wp_update_post(array( 'ID'=>$post->ID, 'menu_order'=>$max+1 )); } }, 99, 3); } }
- The topic ‘Fix for sort order not sticking’ is closed to new replies.