update_menu_item_cache()
云策文档标注
概述
update_menu_item_cache() 函数用于更新菜单项链接对象的文章和分类法缓存,以提高性能。它通过遍历菜单项数组,根据类型收集文章ID或分类法ID,并调用 _prime_post_caches() 或 _prime_term_caches() 进行缓存预加载。
关键要点
- 函数接受一个菜单项对象数组作为参数,仅处理 post_type 为 'nav_menu_item' 的项。
- 通过 _menu_item_type 和 _menu_item_object_id 元数据判断链接类型,收集文章ID或分类法ID。
- 使用 _prime_post_caches() 和 _prime_term_caches() 函数预加载缓存,避免重复数据库查询。
代码示例
function update_menu_item_cache( $menu_items ) {
$post_ids = array();
$term_ids = array();
foreach ( $menu_items as $menu_item ) {
if ( 'nav_menu_item' !== $menu_item->post_type ) {
continue;
}
$object_id = get_post_meta( $menu_item->ID, '_menu_item_object_id', true );
$type = get_post_meta( $menu_item->ID, '_menu_item_type', true );
if ( 'post_type' === $type ) {
$post_ids[] = (int) $object_id;
} elseif ( 'taxonomy' === $type ) {
$term_ids[] = (int) $object_id;
}
}
if ( ! empty( $post_ids ) ) {
_prime_post_caches( $post_ids, false );
}
if ( ! empty( $term_ids ) ) {
_prime_term_caches( $term_ids );
}
}
原文内容
Updates post and term caches for all linked objects for a list of menu items.
Parameters
$menu_itemsWP_Post[]required-
Array of menu item post objects.
Source
function update_menu_item_cache( $menu_items ) {
$post_ids = array();
$term_ids = array();
foreach ( $menu_items as $menu_item ) {
if ( 'nav_menu_item' !== $menu_item->post_type ) {
continue;
}
$object_id = get_post_meta( $menu_item->ID, '_menu_item_object_id', true );
$type = get_post_meta( $menu_item->ID, '_menu_item_type', true );
if ( 'post_type' === $type ) {
$post_ids[] = (int) $object_id;
} elseif ( 'taxonomy' === $type ) {
$term_ids[] = (int) $object_id;
}
}
if ( ! empty( $post_ids ) ) {
_prime_post_caches( $post_ids, false );
}
if ( ! empty( $term_ids ) ) {
_prime_term_caches( $term_ids );
}
}
Changelog
| Version | Description |
|---|---|
| 6.1.0 | Introduced. |