diff --git a/src/wp-includes/formatting.php b/src/wp-includes/formatting.php index e690948ea2..0800f0ef95 100644 --- a/src/wp-includes/formatting.php +++ b/src/wp-includes/formatting.php @@ -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\""; } diff --git a/tests/phpunit/tests/formatting/WPTargetedLinkRel.php b/tests/phpunit/tests/formatting/WPTargetedLinkRel.php index 08f8ac1021..75f34aeda2 100644 --- a/tests/phpunit/tests/formatting/WPTargetedLinkRel.php +++ b/tests/phpunit/tests/formatting/WPTargetedLinkRel.php @@ -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 ) ); + } }