How to append a URL parameter to all outbound URLs

Inbound vs Outbound links:

I guess it’ll be helpful to clarify these concepts:

Inbound links = links from another website to your own website.

Outbound links = links from your website to another website.

An external link would be any link that points to any domain other than the domain the link exists on.

From your comments, I guess what you’re trying to achieve is to modify all your outbound links.

As @MrWhite suggests, you will not be able to change your outbound links by modifying your .htaccess file (it would be helpful, though, if you had to modify your inbound links).

Now, a couple of solutions that can work for you:

Modify your links on the browser (using JavaScript)

This should work (as long as JavaScript is enabled in the user’s browser):

document.addEventListener( "DOMContentLoaded", modify_outbound_links);

function modify_outbound_links(){
    anchors = document.getElementsByTagName('a');
    for (let i = 0; i < anchors.length; i++) {
        let p = anchors[i].href;
        if (p.indexOf('yourdomain.com') === -1) {
            anchors[i].href = p + (p.indexOf('?') != -1 ? "&" : "?") + 'ref=myref';
        }
    }
}

The recommended (and cleanest) option to add some JavaScript to WordPress is using wp_enqueue_script. If you need an easier option, it should work if you just wrap this snippet inside <script> ... </script> and put it inside your footer.php.

Modify your links before they’re served to the user (using WP filters)

You can use WordPress filters (functions that are called when a specific event happens).

In your case, you can use ‘the_content’ filter, which can be used to modify the content of the post after it is retrieved from the database and before it is printed to the screen.

You’d need to add this to your theme’s functions.php file:

add_filter( 'the_content', 'myprefix_modify_outbound_links' ); 

function myprefix_modify_outbound_links( $content ) {

    /* here you can search for all external links in $content and modify them as you wish */

    return $content;
}

Note, this will filter all links in your WordPress posts. You might want to search through your theme’s code, just in case there are other external links.

1 thought on “How to append a URL parameter to all outbound URLs”

  1. I am regular visitor, how are you everybody? This article
    posted at this web site is actually nice.

    Reply

Leave a Comment