From 6ddf0fce946680fa8d27801aa17ea2fa0e11fa05 Mon Sep 17 00:00:00 2001 From: Dave Smith Date: Wed, 24 Nov 2021 16:04:53 +0000 Subject: [PATCH] Use first non-empty Nav post as primary fallback for Nav block (#36740) * Use non-empty Nav post as fallback * Remove code duplication Addresses https://github.com/WordPress/gutenberg/pull/36740#discussion_r754867803 * Extract finding non empty nav block to function * Extract process of getting fallback to dedicated function * Apply block prefix to functions * Add additional safety check around parsing Nav blocks * Extract function for removing null blocks and apply * Check for empty parsed Nav blocks * Improve function comment Addresses https://github.com/WordPress/gutenberg/pull/36740#discussion_r755055265 * Amend ordering params to approximate current wp_nav_menus behaviour * Fetch Nav posts in query rather than filtering in memory Implements suggestion from https://github.com/WordPress/gutenberg/pull/36740#discussion_r755647511 * Improve comments * Spacing * Limit Nav Posts query to a single item Co-authored-by: Adam Zielinski * Fix linting * Improve function naming Co-authored-by: Adam Zielinski Co-authored-by: Adam Zielinski --- .../block-library/src/navigation/index.php | 96 ++++++++++++++++--- 1 file changed, 84 insertions(+), 12 deletions(-) diff --git a/packages/block-library/src/navigation/index.php b/packages/block-library/src/navigation/index.php index 6db226fe960fe..6a3ea8646edef 100644 --- a/packages/block-library/src/navigation/index.php +++ b/packages/block-library/src/navigation/index.php @@ -132,6 +132,83 @@ function block_core_navigation_render_submenu_icon() { return ''; } + +/** + * Finds the first non-empty `wp_navigation` Post. + * + * @return WP_Post|null the first non-empty Navigation or null. + */ +function block_core_navigation_get_first_non_empty_navigation() { + // Order and orderby args set to mirror those in `wp_get_nav_menus` + // see: + // - https://github.com/WordPress/wordpress-develop/blob/ba943e113d3b31b121f77a2d30aebe14b047c69d/src/wp-includes/nav-menu.php#L613-L619. + // - https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters. + $navigation_posts = get_posts( + array( + 'post_type' => 'wp_navigation', + 'order' => 'ASC', + 'orderby' => 'name', + 'posts_per_page' => 1, // only the first post. + 's' => '