How to add target=”_blank” and rel=”noopener” to all external links in WordPress posts

To add rel=”noopener” and target=”_blank” to all external links in WordPress posts, you can use a code snippet in your theme’s functions.php file. Here’s how to do it:

Edit your theme’s functions.php file:

To add the “nofollow” and target=”_blank” attributes to all links in your posts, you can edit your theme’s functions.php file. Follow these steps:

  1. Log in to your WordPress admin dashboard.
  2. Go to “Appearance” > “Theme Editor.”
  3. In the right sidebar, locate and click on the “functions.php” file.
  4. Add the following code snippet at the end of the file:
function add_target_blank_to_external_links($content) {
$site_url = get_site_url();
$pattern = "/<a(.*?)href=[\"'](https?|ftp)(:\/\/)(?!".$site_url.")(.*?)[\"'](.*?)>/i";
$replacement = '<a$1href="$2$3$4"$5 target="_blank" rel="noopener">';
$content = preg_replace($pattern, $replacement, $content);
return $content;
}
add_filter('the_content', 'add_target_blank_to_external_links');
  1. Click “Update File” to save the changes.

This code snippet will add target=”_blank” and rel=”noopener” to all external links in your WordPress posts. Keep in mind that editing your theme’s functions.php file can have unintended consequences if not done correctly. It’s always a good idea to create a backup of your site before making changes to the code.

If you’re using a page builder or any other custom plugin to create content, you may need to use a different method or consult the plugin documentation to add target=”_blank” and rel=”noopener” to external links.

Leave a Reply

Your email address will not be published. Required fields are marked *