Add „Menu“ and „Close“ to WordPress navigation block
Published: – Leave a comment
In the navigation block of the WordPress block editor, you can select whether the mobile menu button should be displayed via icon or text, but not both. To display an icon as well as text aside of it, you need to manually add this content to the button.
This applies for both the menu button to open the mobile menu as well as the button to close it again.
In my case, I want to add “Menu” text before the menu icon and “Close” before the close icon. To do that, I use the filter render_block_core/navigation
and add these text nodes via PHP’s DOMDocument
.
/**
* Add a text to the mobile navigation buttons.
*
* @param string $block_content Block content
* @return string Updated block content
*/
function my_add_button_text( string $block_content ): string {
\libxml_use_internal_errors( true );
$dom = new \DOMDocument();
$dom->loadHTML(
'<html><meta charset="utf-8">' . $block_content . '</html>',
LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD
);
$has_changed = false;
foreach ( $dom->getElementsByTagName( 'button' ) as $button_element ) {
$text = '';
if ( \str_contains( $button_element->getAttribute( 'class' ), 'wp-block-navigation__responsive-container-open' ) ) {
$text = $dom->createTextNode( \esc_html__( 'Menu', 'my-textdomain' ) );
}
else if ( \str_contains( $button_element->getAttribute( 'class' ), 'wp-block-navigation__responsive-container-close' ) ) {
$text = $dom->createTextNode( \esc_html__( 'Close', 'my-textdomain' ) );
}
if ( $text ) {
$button_element->appendChild( $text );
$has_changed = true;
}
}
if ( $has_changed ) {
$block_content = $dom->saveHTML( $dom->documentElement->firstChild->nextSibling ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
}
\libxml_use_internal_errors( false );
return $block_content;
}
\add_filter( 'render_block_core/navigation', 'my_add_button_text' );
Code language: PHP (php)
Since the design is not properly prepare for that, you will need a little bit of CSS to improve it:
.wp-block-navigation__responsive-container-close,
.wp-block-navigation__responsive-container-open {
align-items: center;
flex-direction: row-reverse;
gap: .3em;
}
.wp-block-navigation__responsive-container-close {
display: flex;
}
Code language: CSS (css)
And that’s it, you now have your desired text aside of the menu icons.