If you are searching for a code snippet that will help you to make functionality for external links open in a new window? Then you are at the right place. We will show you to make it easy with this code trick.
We will create an add_action()
hook function to enqueue the custom javascript file and load the file in the header.
Add the above code in the functions.php file.
In the above code, we load the js file. But we don’t have this file yet. So we will create this file and will create the function.
So, first, create the js folder in your active theme and then create the external-links.js file. Now we have a file and we will create a jQuery function. We will check all links on the website and filter the external links and open them in a new window.
Add the following jQuery code in the newly created file (external-links.js)
The above code will find the external links and will add the target attribute to make it open in a new tab.
That’s it.
Tip: Add noopener and noreferrer
If you also want to add noopener
and noreferrer
attributes to those external links then you can do this by adding rel
attribute.
Being Tricky 😉