Created
June 5, 2023 14:08
-
-
Save snrjosh/8d677863ab311e5fecfd3b2a5c45cbc2 to your computer and use it in GitHub Desktop.
Add target="_blank" to external links.
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
| <?php | |
| /** | |
| * https://www.php.net/manual/en/function.substr-replace.php | |
| * https://www.advancedcustomfields.com/resources/acf-load_value/ | |
| */ | |
| /* Add target _blank to external links with ACF field */ | |
| function add_blank_target_to_external_links($value, $post_id, $field) { | |
| // Check if the link is external | |
| if (preg_match('/https?:\/\/(?!' . preg_quote($_SERVER['HTTP_HOST']) . ')/i', $value)) { | |
| //3 is index of h in href; 0 since we're not replacing text. | |
| $value = substr_replace($value, 'target="_blank"', 3, 0); | |
| } | |
| return $value; | |
| } | |
| add_filter('acf/load_value/key=field_601adc4d344be', 'add_blank_target_to_external_links', 10, 3); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment