WordPress.org

Ready to get started?Download WordPress

Forums

How to open all links to a particular site in a new window (3 posts)

  1. TransPersonal
    Member
    Posted 5 years ago #

    I have a lot of links to a particular website, I want all these links to open in a new window or tab. I know about target_blank but I made the mistake of not adding this to the links when I initially made them. I found a couple of plug ins that open external links in new windows and I also found a hack to add to functions.php that does this. But these won't help as I am in a unique dilemma.

    I don't want all external links on my blog to open in a new window, just those from a particular site (let's call it google.com). Can someone please give me the code that will achieve this?

  2. TransPersonal
    Member
    Posted 5 years ago #

    If I was unclear about what I meant in my last post basically what I mean to say is this:

    if this link then open in new window else open in same window

    What would be the PHP way of saying the above.

  3. stvwlf
    Member
    Posted 5 years ago #

    Hi - Adding a few lines of jquery code to your theme's header.php will dynamically add target="_blank" to all links at that domain on any page on which they appear.

    1) find the line <?php wp_head(); ?>

    2) BEFORE that line, add this line
    <?php wp_enqueue_script('jquery'); ?>

    3) AFTER that line, paste this in (change mydomain.com to the domain in question)

    <script type='text/javascript'>
      jQuery(document).ready(function($) {
        $('a[href^="http://mydomain.com"]').attr("target", "_blank");
    });
    </script>

Topic Closed

This topic has been closed to new replies.

About this Topic