We know you can make any link open in popup easily using one of the many available plugins. But this easy installation has drawbacks of their own – a plugin comes with JavaScript files of its own, which upon installation increase the load time of our website – which we do not want under any circumstances.
Why open a link in a popup?
Most of the people who deal with a website need to give references or know more links that do not link back to their own sites. Moreover, these days as social media is the new way of marketing, sharing the posts/articles on social sites becomes a must. At these instances, it is advisable to open these links in a Popup Window rather than the same page or New Tab to avoid the diversion of user’s attention. Opening a link in popup reduces the chance of the user exiting our page and thus helps retain the bounce rates.
When we talk about WordPress, it simply doesn’t allow to make hyperlinks open up in Popup using Inline Scripting which you might already be familiar with.
Let’s see how to open a hyperlink in a popup in WordPress without using a plugin.
Step 1: Copy the code below in a new file and name it popup.js(Make sure that the Save As type is JavaScript and not Normal Text File)
Step 2: Upload the file you just made in the folder named js. It will be there in your themes folder. Generally the path is wp-content/themes/theme-name/js. (This path may vary if you are using a child theme.)
Step 3: For any script to work in WordPress, you need to register it with your theme. For that paste, the code given below in functions.php
Step 4: Add the class “popup” to the link which should want to open in the popup window. For Example
<a href=”http://techmuzz.com” class=”popup”>TechMuzz</a>
Try clicking this => TechMuzz
That’s it! We are done. Simply Add the attribute class=”popup” to any link and it will open up in a popup window.
If you know a better way to open links in a popup window in WordPress then please let us know. In case of any queries, feel free to contact us.
Thank you!!! This is explained so well and works perfectly! 🙂
Simple, but perfect! I like it.
Is it possible to close the window when you click outside this window?
I don’t think so you can detect click events outside of your window scope. If you can find a way to listen to those events then you can use window.close() to close it.
If you are sure that the user will click on your parent window only then in your parent window, you could add JS code to check if it has open any child window or not. If yes then you can close all child windows using their references. This goes without saying that you would have to save all child windows references (popupWindow) into a global variable that you can access them anywhere in the page.
Thank you
TYSM!!!
Wow, this is so cool, it works perfectly