Automatically set page order on create page

You could use ajax and the admin_footer-post-new.php hook. The sql would vary depending on whether you want the highest or most recently published order number. The following returns the highest published order number + 1:

function wpse155926_set_menu_order() {
    $ret = array();

    if ( check_ajax_referer( 'wpse155926_set_menu_order_post', 'nonce', false /*die*/ ) ) {
        global $wpdb;
        //last published
        //$sql = $wpdb->prepare( 'SELECT menu_order FROM ' . $wpdb->posts . ' WHERE post_type = %s AND post_status = %s ORDER BY post_date DESC LIMIT 1', 'page', 'publish' );
        //highest published
        $sql = $wpdb->prepare( 'SELECT menu_order FROM ' . $wpdb->posts . ' WHERE post_type = %s AND post_status = %s ORDER BY menu_order DESC LIMIT 1', 'page', 'publish' );
        if ( ( $result = $wpdb->get_var( $sql ) ) !== false ) {
            $ret['menu_order'] = $result + 1;
        }
    }

    header('Content-type: application/json');
    die( json_encode( $ret ) );
}
add_action( 'wp_ajax_wpse155926_set_menu_order', 'wpse155926_set_menu_order' );

function wpse155926_admin_footer_post_new_php() {
?>
<script type="text/javascript">
jQuery(document).ready(function() {
    (function ($) {
        $.post( ajaxurl, {
                action: 'wpse155926_set_menu_order',
                nonce: <?php echo json_encode( wp_create_nonce( 'wpse155926_set_menu_order_post' ) ); ?>
            }, function(response) {
                if (response && response.menu_order) {
                    $('#pageparentdiv input[name="menu_order"]').val(response.menu_order);
                }
            }, 'json'
        );
    })(jQuery);
});
</script>
<?php
}
add_action( 'admin_footer-post-new.php', 'wpse155926_admin_footer_post_new_php' );

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)