Skip to content

Instantly share code, notes, and snippets.

@richardsweeney
Last active December 14, 2015 15:28
Show Gist options
  • Save richardsweeney/5107646 to your computer and use it in GitHub Desktop.
Save richardsweeney/5107646 to your computer and use it in GitHub Desktop.
WordPress menu filter
<?php
/** Show children only of current page */
add_filter( 'wp_nav_menu_objects', 'olab_nav_menu_objects_start_in', 10, 2 );
function olab_nav_menu_objects_start_in( $sorted_menu_items, $args ) {
global $wp_query;
switch ( $args->menu_id ) {
case 'sidebar-menu' : // change this to the ID of the menu you want to target
$current = false;
$last_parent = false;
$menu = array();
foreach( $sorted_menu_items as $item ) {
// The big daddy, final parent of the current menu item
// If we're already at the last item this will remain false
if ( $item->current_item_ancestor && $item->menu_item_parent == '0' )
$last_parent = $item;
if ( $item->current )
$current = $item;
}
// Only show on relevant pages
if ( $current ) {
$keys = array();
$last_parent = ( !$last_parent ) ? $current : $last_parent;
$children = _olab_submenu_get_children_ids( $last_parent->ID, $sorted_menu_items );
$children[] = $last_parent->ID;
foreach ( $sorted_menu_items as $key => $item ) {
if ( ! in_array( $item->ID, $children ) )
unset( $sorted_menu_items[$key] );
}
$first_item = array_shift( array_values( $sorted_menu_items ) );
$last_item = array_pop( array_values( $sorted_menu_items ) );
$first_item->classes[] = 'first-child';
$last_item->classes[] = 'last-child';
} else {
// Empty the list if there's no parent visible
$sorted_menu_items = array();
}
break;
}
return $sorted_menu_items;
}
/** Helper function for showing the correct menu tree */
function _olab_submenu_get_children_ids( $id, $items ) {
$ids = wp_filter_object_list( $items, array( 'menu_item_parent' => $id ), 'AND', 'ID' );
foreach ( $ids as $id )
$ids = array_merge( $ids, _olab_submenu_get_children_ids( $id, $items ) );
return $ids;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment