danieliser
1/27/2016 - 5:21 AM

This filter and array sorting callback will allow you to set WordPress admin submenu items in specific orders. You can even assign the first

This filter and array sorting callback will allow you to set WordPress admin submenu items in specific orders. You can even assign the first or last positions independently.

This is used to sort the Popup Maker admin menu and allows extensions to reliably be added between Add New & Settings/Support.

<?php

/**
 * Submenu filter function. Tested with Wordpress 4.1.1
 * Sort and order submenu positions to match our custom order.
 *
 * @author Daniel Iser<danieliser@wizardinternetsolutions.com>
 */
function pum_reorder_admin_submenu() {
	global $submenu;

	// Sort the menu according to your preferences
	usort( $submenu['edit.php?post_type=popup'], 'pum_reorder_submenu_array' );
}

add_action( 'admin_head', 'pum_reorder_admin_submenu' );


/**
 * Reorders the submenu by title.
 *
 * Forces $first_pages to load in order at the beginning of the menu
 * and $last_pages to load in order at the end. All remaining menu items will
 * go out in generic order.
 *
 * @author Daniel Iser<danieliser@wizardinternetsolutions.com>
 *
 * @param $a
 * @param $b
 *
 * @return int
 */
function pum_reorder_submenu_array( $a, $b ) {
	$first_pages = apply_filters( 'pum_admin_submenu_first_pages', array(
		__( 'All Popups', 'popup-maker' ),
		__( 'Add New', 'popup-maker' ),
		__( 'All Themes', 'popup-maker' ),
		__( 'Categories', 'popup-maker' ),
		__( 'Tags', 'popup-maker' ),
	) );
	$last_pages  = apply_filters( 'pum_admin_submenu_last_pages', array(
		__( 'Extend', 'popup-maker' ),
		__( 'Settings', 'popup-maker' ),
		__( 'Tools', 'popup-maker' ),
		__( 'Support Forum', 'freemius' ),
		__( 'Contact Us', 'freemius' ),
	) );

	$a_val = strip_tags( $a[0], false );
	$b_val = strip_tags( $b[0], false );

	// Sort First Page Keys.
	if ( in_array( $a_val, $first_pages ) && ! in_array( $b_val, $first_pages ) ) {
		return - 1;
	} elseif ( ! in_array( $a_val, $first_pages ) && in_array( $b_val, $first_pages ) ) {
		return 1;
	} elseif ( in_array( $a_val, $first_pages ) && in_array( $b_val, $first_pages ) ) {
		$a_key = array_search( $a_val, $first_pages );
		$b_key = array_search( $b_val, $first_pages );

		return ( $a_key < $b_key ) ? - 1 : 1;
	}

	// Sort Last Page Keys.
	if ( in_array( $a_val, $last_pages ) && ! in_array( $b_val, $last_pages ) ) {
		return 1;
	} elseif ( ! in_array( $a_val, $last_pages ) && in_array( $b_val, $last_pages ) ) {
		return - 1;
	} elseif ( in_array( $a_val, $last_pages ) && in_array( $b_val, $last_pages ) ) {
		$a_key = array_search( $a_val, $last_pages );
		$b_key = array_search( $b_val, $last_pages );

		return ( $a_key < $b_key ) ? - 1 : 1;
	}

	// Sort remaining keys
	return $a > $b ? 1 : - 1;
}