Skip to content

Commit 122b865

Browse files
committed
Add ability to put .sr-only on the <a> making icon-only items possible
1 parent 4b5af11 commit 122b865

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

class-wp-bootstrap-navwalker.php

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,7 @@ public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0
247247

248248
/** This filter is documented in wp-includes/post-template.php */
249249
$title = apply_filters( 'the_title', $item->title, $item->ID );
250+
250251
/**
251252
* Filters a menu item's title.
252253
*
@@ -259,6 +260,17 @@ public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0
259260
*/
260261
$title = apply_filters( 'nav_menu_item_title', $title, $item, $args, $depth );
261262

263+
/**
264+
* If the .sr-only class was set apply to the nav items text only.
265+
*/
266+
if ( in_array( 'sr-only', $linkmod_classes, true ) ) {
267+
$title = self::wrap_for_screen_reader( $title );
268+
$keys_to_unset = array_keys( $linkmod_classes, 'sr-only' );
269+
foreach($keys_to_unset as $k) {
270+
unset( $linkmod_classes[ $k ] );
271+
}
272+
}
273+
262274
// Put the item contents into $output.
263275
$item_output .= $args->link_before . $icon_html . $title . $args->link_after;
264276

@@ -456,9 +468,11 @@ private function update_atts_for_linkmod_type( $atts = array(), $linkmod_classes
456468
if ( ! empty( $linkmod_classes ) ) {
457469
foreach ( $linkmod_classes as $link_class ) {
458470
if ( ! empty( $link_class ) ) {
459-
// update $atts with a space and the extra classname.
460-
$atts['class'] .= ' ' . esc_attr( $link_class );
461-
471+
// update $atts with a space and the extra classname...
472+
// so long as it's not a sr-only class.
473+
if( 'sr-only' !== $link_class ) {
474+
$atts['class'] .= ' ' . esc_attr( $link_class );
475+
}
462476
// check for special class types we need additional handling for.
463477
if ( 'disabled' === $link_class ) {
464478
// Convert link to '#' and unset open targets.
@@ -475,6 +489,21 @@ private function update_atts_for_linkmod_type( $atts = array(), $linkmod_classes
475489
return $atts;
476490
}
477491

492+
/**
493+
* Wraps the passed text in a screen reader only class.
494+
*
495+
* @since 4.0.0
496+
*
497+
* @param string $text the string of text to be wrapped in a screen reader class.
498+
* @return string the string wrapped in a span with the class.
499+
*/
500+
private function wrap_for_screen_reader( $text = '') {
501+
if ( $text ){
502+
$text = '<span class="sr-only">' . $text . '</span>';
503+
}
504+
return $text;
505+
}
506+
478507
/**
479508
* Returns the correct opening element and attributes for a linkmod.
480509
*

0 commit comments

Comments
 (0)