0

I am preparing a page on my wordpress site where I will post coupons and product urls for a website I am an affiliate of.

Instead of creating affiliate links by hand on every URL, I would like to automatically add the affiliate query parameter on every URL of this particular domain.

The urls might be:

example.com
example.com/
example.com/cell-phones-c_11293/
example.com/cell-phones/pp_617010.html?wid=4

The query parameter I want to add is ?lkid=12345678 (the same for every URL).

example.com?lkid=12345678
example.com/?lkid=12345678
example.com/cell-phones-c_11293/?lkid=12345678
example.com/cell-phones/pp_617010.html?wid=4&lkid=10823628

I want this functionality only for this particular page, not for every post on Wordpress, so I wouldn't like to add the code to the functions.php, or install a plugin just for this single page.

Is it possible to add it as a header or body script to the page through the "Scripts" screen option at the editor?

I have found the following code from this answer,

<script>
var $links = $('a'); // get all anchor tags

// loop through each anchor tag
$.each($links, function(index, item){
    var url = $(this).attr('href'); // var for value of href attribute
            // use regex to match your domain
            var pattern = new RegExp(/(example.com\/)(.*)/i);
            if(pattern.test(url))
                $(this).attr('href', url + '?lkid=12345678');
                // append ?lkid=12345678 if url contains example
});
</script>

And the following code from this answer

<script>
function updateQueryStringParameter(uri, key, value) {
  var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
  var separator = uri.indexOf('?') !== -1 ? "&" : "?";
  if (uri.match(re)) {
    return uri.replace(re, '$1' + key + "=" + value + '$2');
  }
  else {
    return uri + separator + key + "=" + value;
  }
}
</script>

...but I unfortunately I don't know enough programming to make them work for my case.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • I've edited my post and added a solution that works both for links that already have a query string, and those that don't. – thephpdev Jun 08 '17 at 20:55

2 Answers2

0

This code adds the parameter if it doesn't already have a query string, and will parse, add the parameter, and re-encode for links that already have a query string:

<!DOCTYPE html>
<html>
    <head>
        <title>></title>
    </head>
    <body>
        <a href="http://www.example.com">Test</a>
        <a href="//www.google.com?test=1">Test</a>
        <a href="http://www.example.com/?test=1">Test</a>
        <a href="www.example.com?test=1">Test</a>
        <a href="../?test=1&another=2">Test</a>
        <a href="?test=1&another=2">Test</a>
        <script>
            // parseQuery: Originally from StackOverflow of: https://stackoverflow.com/a/13419367/2529423
            function parseQuery(qstr) {
                var query = {};
                var a = (qstr[0] === '?' ? qstr.substr(1) : qstr).split('&');
                for (var i = 0; i < a.length; i++) {
                    var b = a[i].split('=');
                    query[decodeURIComponent(b[0])] = decodeURIComponent(b[1] || '');
                }
                return query;
            }

            // encodeQuery originally from StackOverflow: https://stackoverflow.com/a/1714899/2529423
            function encodeQuery(obj) {
              var str = [];
              for(var p in obj)
                if (obj.hasOwnProperty(p)) {
                  str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                }
              return str.join("&");
            }

            function addQueryParameterToDomain(key, value, conditionDomain) {
                var links = document.querySelectorAll('a[href]'),
                    linksLength = links.length,
                    index,
                    queryIndex,
                    queryString,
                    query,
                    url,
                    domain,
                    colonSlashSlash;

                // Iterate through and add query paramter
                for(index = 0; index < linksLength; ++index) {
                    url = links[index].href,
                    queryIndex = url.indexOf('?'),
                    colonSlashSlash = url.indexOf('://');

                    domain = url.substring(colonSlashSlash + 3);
                    domain = domain.substring(0, domain.indexOf('/'));

                    if(domain !== conditionDomain) {
                        continue;
                    }

                    if(queryIndex === -1) {
                        url += '?' + key + '=' + value;
                    } else {
                        queryString = url.substring(queryIndex);
                        url = url.substring(0, queryIndex);
                        query = parseQuery(queryString);

                        query[key] = value;

                        url += '?' + encodeQuery(query);
                    }

                    links[index].href = url;
                }
            }

            jQuery(function() {
                addQueryParameterToDomain('lkid', '12345678', 'example.com');
                addQueryParameterToDomain('lkid', '12345678', 'www.example.com');
            });
        </script>
    </body>
</html>

All you'll need to do is replace the script you have with the contents of the <script> tag above, and bob's your uncle.

thephpdev
  • 1,097
  • 10
  • 25
  • Thank you for the awesome code. Just one little request: is it possible to add the query on only the example.com links? Because the current code adds it to every link on the page, the menu links, the ad links, the lot. – Angelos Kyritsis Jun 08 '17 at 21:56
  • @AngelosKyritsis, just realised you even said that in your question. Sorry about that, I sometimes don't read things properly. – thephpdev Jun 08 '17 at 23:12
0

First answer looks to work except if the href already has some parameters (?x=y). Also, it's advisable to put jQuery code inside .ready function. And last, in wordpress by default you need to use jQuery instead of $ alias, or pass $ into the function, which I'm doing here:

<script>
jQuery(document).ready(function( $ ){
    var $links = $('a'); // get all anchor tags

    // loop through each anchor tag
    $.each($links, function(index, item){
        var url = $(this).attr('href'); // var for value of href attribute
            // use regex to match your domain
            var pattern = new RegExp(/(example.com\/)(.*)/i);
            if(pattern.test(url))
                var chr = url.indexOf("?") == -1 ? "?" : "&"; // will be "&" if "?" in url
                $(this).attr('href', url + chr + 'lkid=12345678');
                // append ?lkid=12345678 if url contains example
    });
});
</script>

Give it a shot and if it works for you I'll make some improvements for the parameters.

yezzz
  • 2,990
  • 1
  • 10
  • 19
  • This still won't work if the link already has query string parameters, I've edited my posted and added my script now. As `?test=1&another=2?lkid=12345678` is not a valid query string. – thephpdev Jun 08 '17 at 20:55
  • I'm aware of that... read the first line of my answer. Also OP said he doesn't like to add the code to the functions.php. – yezzz Jun 08 '17 at 21:00
  • 1
    Read my answer again, it doesn't use PHP now. – thephpdev Jun 08 '17 at 21:00
  • It works, @yezzz. If you can add a little something to check if the link already has query string parameters, it will be perfect. – Angelos Kyritsis Jun 08 '17 at 22:00
  • I'll put in a simple check for '?' being in the url. Not foolproof, so you may want to go with phpdev answer – yezzz Jun 08 '17 at 23:25