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
This commit is contained in:
Gary Pendergast 2019-04-08 23:05:22 +00:00
parent 8efcc32fde
commit 466a7443a6
2 changed files with 77 additions and 4 deletions

View File

@ -169,10 +169,14 @@ class Walker_Nav_Menu extends Walker {
$output .= $indent . '<li' . $id . $class_names . '>'; $output .= $indent . '<li' . $id . $class_names . '>';
$atts = array(); $atts = array();
$atts['title'] = ! empty( $item->attr_title ) ? $item->attr_title : ''; $atts['title'] = ! empty( $item->attr_title ) ? $item->attr_title : '';
$atts['target'] = ! empty( $item->target ) ? $item->target : ''; $atts['target'] = ! empty( $item->target ) ? $item->target : '';
$atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : ''; if ( '_blank' === $item->target && empty( $item->xfn ) ) {
$atts['rel'] = 'noopener noreferrer';
} else {
$atts['rel'] = $item->xfn;
}
$atts['href'] = ! empty( $item->url ) ? $item->url : ''; $atts['href'] = ! empty( $item->url ) ? $item->url : '';
$atts['aria-current'] = $item->current ? 'page' : ''; $atts['aria-current'] = $item->current ? 'page' : '';

View File

@ -0,0 +1,69 @@
<?php
/**
* @group navmenus
* @group walker
*/
class Tests_Walker_Nav_Menu extends WP_UnitTestCase {
/**
* @var \Walker_Nav_Menu The instance of the walker.
*/
public $walker;
/**
* Setup.
*/
public function setUp() {
global $_wp_nav_menu_max_depth;
parent::setUp();
/** Walker_Nav_Menu_Edit class */
require_once ABSPATH . 'wp-includes/class-walker-nav-menu.php';
$this->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( "<li id=\"menu-item-{$post_id}\" class=\"menu-item-{$post_id}\"><a target=\"_blank\" rel=\"noopener noreferrer\">{$post_title}</a>", $expected );
}
}