Skip to content

Instantly share code, notes, and snippets.

@gmaggio
Created August 10, 2014 01:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gmaggio/08a2459b39c3b05b44a3 to your computer and use it in GitHub Desktop.
Save gmaggio/08a2459b39c3b05b44a3 to your computer and use it in GitHub Desktop.
[Wordpress] Automatically set MENU ORDER on create new PAGE. Sources: http://wordpress.stackexchange.com/a/155979/1044, http://wordpress.stackexchange.com/a/155974/1044
<?php
/**
* Automatically set Menu Order on create new page
*
* Source:
* http://wordpress.stackexchange.com/a/155979/1044
*
*/
add_action( 'admin_footer-post-new.php', 'my_admin_footer_post_new_php' );
function my_set_menu_order() {
$ret = array();
if ( check_ajax_referer('my_set_menu_order_post', 'nonce', false /*die*/) ) {
global $wpdb;
// Get the last page order available
$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 ) {
// Set as the new last page order
$ret['menu_order'] = ++$result;
}
}
header('Content-type: application/json');
die( json_encode( $ret ) );
}
add_action( 'wp_ajax_my_set_menu_order', 'my_set_menu_order' );
function my_admin_footer_post_new_php() {
?>
<script type="text/javascript">
jQuery(document).ready(function() {
(function ($) {
$.post( ajaxurl, {
action: 'my_set_menu_order',
nonce: <?php echo json_encode( wp_create_nonce( 'my_set_menu_order_post' ) ); ?>
}, function(response) {
if (response && response.menu_order) {
$('#pageparentdiv input[name="menu_order"]').val(response.menu_order);
}
}, 'json'
);
})(jQuery);
});
</script>
<?php
}
<?php
/**
* Automatically set Menu Order on create new page
* (Alternative method)
*
* Source:
* http://wordpress.stackexchange.com/a/155974/1044
*
*/
add_action( 'publish_page', 'my_set_to_last_page', 10, 2 );
function my_set_to_last_page( $ID, $post ) {
if ( ! wp_is_post_revision( $ID ) ){
if ( $post->menu_order === 0 ) {
global $wpdb;
$query = "SELECT menu_order FROM $wpdb->posts WHERE post_type = 'page' AND post_status = 'publish' ORDER BY menu_order DESC LIMIT 1";
$max_menu_order = $wpdb->get_var( $query );
$post->menu_order = ++$max_menu_order;
// unhook this function so it doesn't loop infinitely
remove_action('publish_page', 'my_set_to_last_page');
// update the post, which calls save_post again
wp_update_post( $post );
// re-hook this function
add_action('publish_page', 'my_set_to_last_page');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment