BuddyDev

Search

[Resolved] Open all external activity links in a new browser tab

  • Participant
    Level: Guru
    Posts: 771
    Tosin on #28316

    Hello,

    How can I automatically make all external activity links open in a new browser tab

    Thanks

  • Keymaster
    (BuddyDev Team)
    Posts: 22489
    Brajesh Singh on #28321

    Hi Tosin,
    Thank you for the question..
    What is external link in activity(It is normal link added as text or added via some plugin?)

    Regards
    Brajesh

  • Participant
    Level: Guru
    Posts: 771
    Tosin on #28328

    The external link is normal links added as text to external websites. If this can be applied across the whole website would be awesome not just activity page only.

  • Participant
    Level: Guru
    Posts: 771
    Tosin on #47715

    I found this code

     function open_external_links_in_new_tab() {
      echo '<script type="text/javascript">';
      echo 'var links = document.getElementsByTagName("a");';
      echo 'for (var i = 0; i < links.length; i++) {';
      echo 'var link = links[i];';
      echo 'if (link.hostname != window.location.hostname) {';
      echo 'link.target = "_blank";';
      echo '}';
      echo '}';
      echo '</script>';
    }
    add_action( 'wp_footer', 'open_external_links_in_new_tab' ); 

    Kindly review

  • Keymaster
    (BuddyDev Team)
    Posts: 22489
    Brajesh Singh on #47726

    Hi Tosin,
    This will work for the first page but not for subsequent pages of activity. It will stop as soon as you load the 2nd page of activity(using load more).

    A proper solution would be to either do it via php using regex or client side with the modification of code using MutationObserver in addition to the above code.

    Regards
    Brajesh

  • Participant
    Level: Guru
    Posts: 771
    Tosin on #47734

    What about this

     function open_external_links_in_new_tab_bp_activity( $query_string, $object ) {
      if ( $object != 'activity' ) {
        return $query_string;
      }
      ?>
      <script type="text/javascript">
      var links = document.getElementsByTagName("a");
      for (var i = 0; i < links.length; i++) {
        var link = links[i];
        if (link.hostname != window.location.hostname) {
          link.target = "_blank";
        }
      }
      </script>
      <?php
      return $query_string;
    }
    add_filter( 'bp_ajax_querystring', 'open_external_links_in_new_tab_bp_activity', 10, 2 ); 
  • Participant
    Level: Guru
    Posts: 771
    Tosin on #47735
    This reply has been marked as private.
  • Keymaster
    (BuddyDev Team)
    Posts: 22489
    Brajesh Singh on #47736
    This reply has been marked as private.
  • Participant
    Level: Guru
    Posts: 771
    Tosin on #47740
    This reply has been marked as private.
  • Participant
    Level: Guru
    Posts: 771
    Tosin on #47741
    This reply has been marked as private.

You must be logged in to reply to this topic.

This topic is: resolved