Render link description in navigation block

I solve this problem by using WordPress Filter hooks

I use the filter render_block, to hook in altering the existing HTML

So I created custom_render_block_core_navigation_submenu hook function.

Inside my hook I am using conditions to avoid storing my modified code in the database.

  • Target the type of block (core/navigation-submenu)

  • Only render in the front-end

  • Don’t alter the HTML in wp-json

In the function I check is title or description is avaliable, if yes, I create new list item element with title and/or description and insert this list item inside child list right after the opening

function custom_render_block_core_navigation_submenu(string $block_content, array $block): string
{
    if (
        isset($block['blockName']) &&
        'core/navigation-submenu' === $block['blockName'] &&
        !is_admin() &&
        !wp_is_json_request()
    ) {
        $additional_html="";

        // Add description if available.
        if (!empty($block['attrs']['title']) || !empty($block['attrs']['description'])) {
            $additional_html .= '<li class="wp-block-navigation-item">';

            // Add title if available.
            if (!empty($block['attrs']['title'])) {
                $additional_html .= '<span class="wp-block-navigation-item__label">';
                $additional_html .= wp_kses_post($block['attrs']['title']);
                $additional_html .= '</span>';
            }

            // Add description if available.
            if (!empty($block['attrs']['description'])) {
                $additional_html .= '<span class="wp-block-navigation-item__description">';
                $additional_html .= wp_kses_post($block['attrs']['description']);
                $additional_html .= '</span>';
            }

            $additional_html .= '</li>';
        }

        // Find the position to insert $additional_html
        $position = strpos($block_content, '<ul class="wp-block-navigation__submenu-container wp-block-navigation-submenu">');
        if ($position !== false) {
            // Insert $additional_html right after the opening <ul> tag
            $position += strlen('<ul class="wp-block-navigation__submenu-container wp-block-navigation-submenu">');
            $block_content = substr_replace($block_content, $additional_html, $position, 0);
        }
    }

    return $block_content;
}

add_filter('render_block', 'custom_render_block_core_navigation_submenu', null, 2);

tech