Formatting: Adjust wp_targeted_link_rel() to ensure JSON format is preserved and correct quotes are used when adding the missing rel attribute.

Props birgire, TobiasBg, fierevere, audrasjb, SergeyBiryukov.
Fixes #46316, #47244.

git-svn-id: https://develop.svn.wordpress.org/trunk@45348 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Sergey Biryukov 2019-05-17 12:08:50 +00:00
parent ee8771923a
commit a36aa1b078
2 changed files with 30 additions and 0 deletions

View File

@ -3094,6 +3094,10 @@ function wp_targeted_link_rel_callback( $matches ) {
$delimiter = trim( $rel_match[1] ) ? $rel_match[1] : '"';
$rel = 'rel=' . $delimiter . trim( implode( ' ', $parts ) ) . $delimiter;
$link_html = str_replace( $rel_match[0], $rel, $link_html );
} elseif ( preg_match( '|target\s*=\s*?\\\\"|', $link_html ) ) {
$link_html .= " rel=\\\"$rel\\\"";
} elseif ( preg_match( '#(target|href)\s*=\s*?\'#', $link_html ) ) {
$link_html .= " rel='$rel'";
} else {
$link_html .= " rel=\"$rel\"";
}

View File

@ -101,4 +101,30 @@ class Tests_Targeted_Link_Rel extends WP_UnitTestCase {
$this->assertEquals( $expected, $post->post_content );
}
/**
* Ensure JSON format is preserved when relation attribute (rel) is missing.
*
* @ticket 46316
*/
public function test_wp_targeted_link_rel_should_preserve_json() {
$content = '<p>Links: <a href=\"\/\" target=\"_blank\">No rel<\/a><\/p>';
$expected = '<p>Links: <a href=\"\/\" target=\"_blank\" rel=\"noopener noreferrer\">No rel<\/a><\/p>';
$this->assertEquals( $expected, wp_targeted_link_rel( $content ) );
}
/**
* Ensure correct quotes are used when relation attribute (rel) is missing.
*
* @ticket 47244
*/
public function test_wp_targeted_link_rel_should_use_correct_quotes() {
$content = '<p>Links: <a href=\'\/\' target=\'_blank\'>No rel<\/a><\/p>';
$expected = '<p>Links: <a href=\'\/\' target=\'_blank\' rel=\'noopener noreferrer\'>No rel<\/a><\/p>';
$this->assertEquals( $expected, wp_targeted_link_rel( $content ) );
$content = '<p>Links: <a href=\'\/\' target=_blank>No rel<\/a><\/p>';
$expected = '<p>Links: <a href=\'\/\' target=_blank rel=\'noopener noreferrer\'>No rel<\/a><\/p>';
$this->assertEquals( $expected, wp_targeted_link_rel( $content ) );
}
}