Menus: Improve cache priming in the `wp_get_nav_menu_items` function.

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

Built from https://develop.svn.wordpress.org/trunk@52975


git-svn-id: http://core.svn.wordpress.org/trunk@52564 1a063a9b-81f0-0310-95a4-ce76da25c4cd
This commit is contained in:
spacedmonkey 2022-03-22 09:58:07 +00:00
parent 41de51364a
commit 7613aaf9b1
2 changed files with 13 additions and 31 deletions

View File

@ -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 );

View File

@ -16,7 +16,7 @@
*
* @global string $wp_version
*/
$wp_version = '6.0-alpha-52974';
$wp_version = '6.0-alpha-52975';
/**
* Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.