From 466a7443a6cac9c067361880bad3e4aad849c100 Mon Sep 17 00:00:00 2001 From: Gary Pendergast Date: Mon, 8 Apr 2019 23:05:22 +0000 Subject: [PATCH] Menus: Add `rel="noopener"` to `target="_blank"` links by default in menus. This expands upon `rel="noopener"` being previously added to links in the content. Props audrasjb, welcher. Fixes #43290. git-svn-id: https://develop.svn.wordpress.org/trunk@45141 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/class-walker-nav-menu.php | 12 ++-- tests/phpunit/tests/menu/walker-nav-menu.php | 69 ++++++++++++++++++++ 2 files changed, 77 insertions(+), 4 deletions(-) create mode 100644 tests/phpunit/tests/menu/walker-nav-menu.php diff --git a/src/wp-includes/class-walker-nav-menu.php b/src/wp-includes/class-walker-nav-menu.php index f46f14c177..171243b1b9 100644 --- a/src/wp-includes/class-walker-nav-menu.php +++ b/src/wp-includes/class-walker-nav-menu.php @@ -169,10 +169,14 @@ class Walker_Nav_Menu extends Walker { $output .= $indent . ''; - $atts = array(); - $atts['title'] = ! empty( $item->attr_title ) ? $item->attr_title : ''; - $atts['target'] = ! empty( $item->target ) ? $item->target : ''; - $atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : ''; + $atts = array(); + $atts['title'] = ! empty( $item->attr_title ) ? $item->attr_title : ''; + $atts['target'] = ! empty( $item->target ) ? $item->target : ''; + if ( '_blank' === $item->target && empty( $item->xfn ) ) { + $atts['rel'] = 'noopener noreferrer'; + } else { + $atts['rel'] = $item->xfn; + } $atts['href'] = ! empty( $item->url ) ? $item->url : ''; $atts['aria-current'] = $item->current ? 'page' : ''; diff --git a/tests/phpunit/tests/menu/walker-nav-menu.php b/tests/phpunit/tests/menu/walker-nav-menu.php new file mode 100644 index 0000000000..e60a9550d4 --- /dev/null +++ b/tests/phpunit/tests/menu/walker-nav-menu.php @@ -0,0 +1,69 @@ +walker = new Walker_Nav_Menu(); + + $this->_wp_nav_menu_max_depth = $_wp_nav_menu_max_depth; + parent::setUp(); + } + + /** + * Tear down + */ + public function tearDown() { + global $_wp_nav_menu_max_depth; + + $_wp_nav_menu_max_depth = $this->_wp_nav_menu_max_depth; + parent::tearDown(); + } + + /** + * Tests when an items target it _blank, that rel="'noopener noreferrer" is added. + * + * @ticket #43290 + */ + public function test_noopener_no_referrer_for_target_blank() { + $expected = ''; + $post_id = $this->factory->post->create(); + $post_title = get_the_title( $post_id ); + + $item = array( + 'ID' => $post_id, + 'object_id' => $post_id, + 'title' => $post_title, + 'target' => '_blank', + 'xfn' => '', + 'current' => false, + ); + + $args = array( + 'before' => '', + 'after' => '', + 'link_before' => '', + 'link_after' => '', + ); + + $this->walker->start_el( $expected, (object) $item, 0, (object) $args ); + + $this->assertSame( "
  • {$post_title}", $expected ); + } +}