Define menu_order on Creation of New Custom Post?

I’ve created a custom post type called video and I’m using a plugin called Playlist_Order (which changes the menu_order field) to allow the user to use a drag and drop interface to order their videos in a playlist.

However, when adding a new post the video appears at the top of the playlist because it’s given a default menu_order value of 0.

Read More

On creation of a new video post I would like it to appear last in the playlist – i.e. query all video post types, find the largest menu_order value and then set this +1 for the new post.

How can I implement this?

Related posts

Leave a Reply

3 comments

  1. Hi @fxfuture:

    I think what you are looking for is the wp_insert_post_data hook. You can add this code to the bottom of your theme’s functions.php file and/or you can add it to a plugin:

    add_filter('wp_insert_post_data','my_wp_insert_post_data',10,2);
    function my_wp_insert_post_data($data, $postarr) {
      $post_type = 'video';
      if ($data['post_type']==$post_type && get_post($postarr['ID'])->post_status=='draft') {
        global $wpdb;
        $data['menu_order'] = $wpdb->get_var("SELECT MAX(menu_order)+1 AS menu_order FROM {$wpdb->posts} WHERE post_type='{$post_type}'");
      }
      return $data;
    }
    
  2. Updated the answer as the post_status draft gave a notice
    this will give ALL CPT = page with a zero menu order a unique menu order (highest in database + 5). Adjust to your needs.

    add_filter( 'wp_insert_post_data', 'mp_wp_insert_post_data', 999, 2);
    function mp_wp_insert_post_data( $data, $postarr ) {
      $post_type = 'page';
      if( $data['post_type'] == 'page' && $data['menu_order'] == 0 ) {
        global $wpdb;
        $data['menu_order'] = $wpdb->get_var("SELECT MAX(menu_order)+5 AS menu_order FROM {$wpdb->posts} WHERE post_type='{$post_type}'");
      }
      return $data;
    }