Reduce number of queries in wp_get_nav_menu_items() by fetching posts and terms with batch queries. see #12734

git-svn-id: http://svn.automattic.com/wordpress/trunk@14557 1a063a9b-81f0-0310-95a4-ce76da25c4cd
This commit is contained in:
ryan 2010-05-11 14:21:03 +00:00
parent 5c48b8b015
commit 69d0ec946e
1 changed files with 49 additions and 20 deletions

View File

@ -412,32 +412,61 @@ function wp_get_nav_menu_items( $menu, $args = array() ) {
$items = get_objects_in_term( $menu->term_id, 'nav_menu' ); $items = get_objects_in_term( $menu->term_id, 'nav_menu' );
if ( ! empty( $items ) ) { if ( empty( $items ) )
$defaults = array( 'order' => 'ASC', 'orderby' => 'menu_order', 'post_type' => 'nav_menu_item', 'post_status' => 'publish', 'output' => ARRAY_A, 'output_key' => 'menu_order', 'nopaging' => true, return $items;
'update_post_term_cache' => false);
$args = wp_parse_args( $args, $defaults );
if ( count( $items ) > 1 )
$args['include'] = implode( ',', $items );
else
$args['include'] = $items[0];
$items = get_posts( $args ); $defaults = array( 'order' => 'ASC', 'orderby' => 'menu_order', 'post_type' => 'nav_menu_item', 'post_status' => 'publish', 'output' => ARRAY_A, 'output_key' => 'menu_order', 'nopaging' => true,
'update_post_term_cache' => false);
$args = wp_parse_args( $args, $defaults );
if ( count( $items ) > 1 )
$args['include'] = implode( ',', $items );
else
$args['include'] = $items[0];
if ( is_wp_error( $items ) || ! is_array( $items ) ) { $items = get_posts( $args );
return false;
}
$items = array_map( 'wp_setup_nav_menu_item', $items ); if ( is_wp_error( $items ) || ! is_array( $items ) )
return false;
if ( ARRAY_A == $args['output'] ) { // Get all posts and terms at once to prime the caches
$GLOBALS['_menu_item_sort_prop'] = $args['output_key']; $posts = array();
usort($items, '_sort_nav_menu_items'); $terms = array();
$i = 1; foreach ( $items as $item ) {
foreach( $items as $k => $item ) { $object_id = get_post_meta( $item->ID, '_menu_item_object_id', true );
$items[$k]->$args['output_key'] = $i++; $object = get_post_meta( $item->ID, '_menu_item_object', true );
} $type = get_post_meta( $item->ID, '_menu_item_type', true );
if ( 'post_type' == $type )
$posts[$object][] = $object_id;
elseif ( 'taxonomy' == $type)
$terms[$object][] = $object_id;
}
if ( !empty($posts) ) {
foreach ( array_keys($posts) as $post_type ) {
get_posts( array('post__in' => $posts[$post_type], 'post_type' => $post_type, 'nopaging' => true, 'update_post_term_cache' => false) );
} }
} }
unset($posts);
if ( !empty($terms) ) {
foreach ( array_keys($terms) as $taxonomy ) {
get_terms($taxonomy, array('include' => $terms[$taxonomy]) );
}
}
unset($terms);
$items = array_map( 'wp_setup_nav_menu_item', $items );
if ( ARRAY_A == $args['output'] ) {
$GLOBALS['_menu_item_sort_prop'] = $args['output_key'];
usort($items, '_sort_nav_menu_items');
$i = 1;
foreach( $items as $k => $item ) {
$items[$k]->$args['output_key'] = $i++;
}
}
return $items; return $items;
} }