Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Navigation link: prime caches for all posts in menu items #40752

Merged
merged 11 commits into from
May 9, 2022
39 changes: 39 additions & 0 deletions packages/block-library/src/navigation/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,40 @@ function block_core_navigation_get_fallback_blocks() {
return apply_filters( 'block_core_navigation_render_fallback', $fallback_blocks );
}

/**
* Iterate through all inner blocks recursively and get navigation link block's post ids..
*
* @param WP_Block_List $inner_blocks Block list class instance.
*
* @return array Array of post ids.
*/
function block_core_navigation_get_post_ids( $inner_blocks ){
$post_list = array_map( 'get_post_id_from_navigation_blocks', iterator_to_array( $inner_blocks ) );
spacedmonkey marked this conversation as resolved.
Show resolved Hide resolved
return array_unique( array_merge( ...$post_list ) );
spacedmonkey marked this conversation as resolved.
Show resolved Hide resolved
}

/**
* Get post ids from a navigation link block instance.
*
* @param WP_Block $block Instance of a block.
*
* @return array Array of post ids.
*/
function get_post_id_from_navigation_block( $block ) {
spacedmonkey marked this conversation as resolved.
Show resolved Hide resolved
$post_ids = array();

if ( $block->inner_blocks ) {
$post_ids = block_core_navigation_get_post_ids( $block->inner_blocks );
}
if ( 'core/navigation-link' === $block->name || 'core/navigation-submenu' === $block->name ) {
if ( $block->attributes && isset( $block->attributes['kind'] ) && $block->attributes['kind'] === 'post-type' ) {
$post_ids[] = $block->attributes['id'];
}
}

return $post_ids;
}

/**
* Renders the `core/navigation` block on server.
*
Expand Down Expand Up @@ -506,6 +540,11 @@ function render_block_core_navigation( $attributes, $content, $block ) {
$text_decoration ? array( $text_decoration_class ) : array()
);

$post_ids = block_core_navigation_get_post_ids( $inner_blocks );
if ( $post_ids ) {
_prime_post_caches( $post_ids, false, false );
}

$inner_blocks_html = '';
$is_list_open = false;
foreach ( $inner_blocks as $inner_block ) {
Expand Down