Skip to content

Instantly share code, notes, and snippets.

@ashwebstudio
Last active November 8, 2018 05:54
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 ashwebstudio/3bac0d3567312a8a73f421f14e52fab1 to your computer and use it in GitHub Desktop.
Save ashwebstudio/3bac0d3567312a8a73f421f14e52fab1 to your computer and use it in GitHub Desktop.
WordPress: Make nav menu items appear randomly
<?php
// You must add a class "random" to each nav menu item you wish to be randomized
add_filter( 'wp_nav_menu_objects', 'random_menu_items', 10, 2 );
function random_menu_items( $menu, $args ) {
$shuffle_array = array();
foreach ( $menu as $key => $item ) { // Loop through the menu items
if ( in_array( 'random', $item->classes ) ) { // See if this menu item has class "random"
$shuffle_array[] = $menu[ $key ]; // Put menu item into new array to be randomized
unset( $menu[ $key ] ); // Remove this from the main menu array
}
}
if ( !empty( $shuffle_array ) ) { // If we find any menu items to be randomized
shuffle( $shuffle_array ); // Do the randomization of the selected menu items
$menu = array_merge( $menu, $shuffle_array ); // Merge the two arrays together
}
return $menu;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment