Created
January 2, 2026 22:05
-
-
Save taricco/999b61240c00d7ab758db307c1ed843f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Use 'utility_new-window-link' GenerateBlocks Global Style | |
| add_filter( 'render_block', function ( $block_content, $block ) { | |
| if ( is_admin() ) return $block_content; | |
| // Only touch blocks that actually output your utility class. | |
| if ( strpos( $block_content, 'utility_new-window-link' ) === false ) { | |
| return $block_content; | |
| } | |
| // 1) Add target="_blank" if missing. | |
| $block_content = preg_replace( | |
| '~<a(?![^>]*\btarget=)([^>]*)>~i', | |
| '<a target="_blank"$1>', | |
| $block_content | |
| ); | |
| // 2) Ensure rel contains noopener noreferrer. | |
| // If rel exists, append missing tokens. If not, add rel. | |
| $block_content = preg_replace_callback( | |
| '~<a\b([^>]*)>~i', | |
| function ( $m ) { | |
| $attrs = $m[1]; | |
| // Only act on links that open in a new tab. | |
| if ( ! preg_match( '~\btarget\s*=\s*([\'"])_blank\1~i', $attrs ) ) { | |
| return '<a' . $attrs . '>'; | |
| } | |
| if ( preg_match( '~\brel\s*=\s*([\'"])(.*?)\1~i', $attrs, $relm ) ) { | |
| $quote = $relm[1]; | |
| $rel = $relm[2]; | |
| $tokens = preg_split( '/\s+/', trim( $rel ) ); | |
| $tokens = array_filter( $tokens ); | |
| foreach ( array( 'noopener', 'noreferrer' ) as $need ) { | |
| if ( ! in_array( $need, $tokens, true ) ) { | |
| $tokens[] = $need; | |
| } | |
| } | |
| $new_rel = implode( ' ', $tokens ); | |
| $attrs = preg_replace( | |
| '~\brel\s*=\s*([\'"])(.*?)\1~i', | |
| 'rel=' . $quote . $new_rel . $quote, | |
| $attrs, | |
| 1 | |
| ); | |
| return '<a' . $attrs . '>'; | |
| } | |
| // No rel attribute — add one. | |
| return '<a' . $attrs . ' rel="noopener noreferrer">'; | |
| }, | |
| $block_content | |
| ); | |
| return $block_content; | |
| }, 99, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment