From ac37883b610159c070fee1c595ba1f68dff8722c Mon Sep 17 00:00:00 2001 From: Jonny Harris Date: Tue, 22 Mar 2022 09:56:59 +0000 Subject: [PATCH] Menus: Improve cache priming in the `wp_get_nav_menu_items` function. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In `wp_get_nav_menu_items` multiple function calls to `get_terms` and `get_posts` were being used to load post/term objects into memory. This change replaces calls to `get_terms` and `get_posts` with calls to `_prime_post_caches` and  `_prime_term_caches`. These functions are designed to prime object caches and do not have the overhead of a query object. This change also replaces multiple queries with a single query, saving many SQL queries per page load. Props Spacedmonkey, peterwilsoncc. Fixes #55428. --This line, and those below, will be ignored-- M src/wp-includes/nav-menu.php git-svn-id: https://develop.svn.wordpress.org/trunk@52975 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/nav-menu.php | 42 +++++++++++------------------------- 1 file changed, 12 insertions(+), 30 deletions(-) diff --git a/src/wp-includes/nav-menu.php b/src/wp-includes/nav-menu.php index abfe4a0149..d450928ebb 100644 --- a/src/wp-includes/nav-menu.php +++ b/src/wp-includes/nav-menu.php @@ -716,49 +716,31 @@ function wp_get_nav_menu_items( $menu, $args = array() ) { $items = array(); } - // Get all posts and terms at once to prime the caches. - if ( empty( $fetched[ $menu->term_id ] ) && ! wp_using_ext_object_cache() ) { + // Prime posts and terms caches. + if ( empty( $fetched[ $menu->term_id ] ) ) { $fetched[ $menu->term_id ] = true; - $posts = array(); - $terms = array(); + $post_ids = array(); + $term_ids = array(); foreach ( $items as $item ) { $object_id = get_post_meta( $item->ID, '_menu_item_object_id', true ); - $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; + $post_ids[] = (int) $object_id; } elseif ( 'taxonomy' === $type ) { - $terms[ $object ][] = $object_id; + $term_ids[] = (int) $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, - ) - ); - } + if ( ! empty( $post_ids ) ) { + _prime_post_caches( $post_ids, false ); } - unset( $posts ); + unset( $post_ids ); - if ( ! empty( $terms ) ) { - foreach ( array_keys( $terms ) as $taxonomy ) { - get_terms( - array( - 'taxonomy' => $taxonomy, - 'include' => $terms[ $taxonomy ], - 'hierarchical' => false, - ) - ); - } + if ( ! empty( $term_ids ) ) { + _prime_term_caches( $term_ids ); } - unset( $terms ); + unset( $term_ids ); } $items = array_map( 'wp_setup_nav_menu_item', $items );