1

I need to be able to automatically change normal links to affiliate links on my Wordpress website.

For example: when I add a GOG.com link, it should automatically append my partner ID at the end of this URL so it would look like that - GOG.com/my-affiliate-id.

Does anyone know how can I do that? I have hundreds of links on my website so I would like to make it as light as possible.

Thank you, Kacper

  • Add the link to where? How would we know if the link is actually an affiliate link? You don't want to append the ID to just any links, do you? – Sally CJ Mar 12 at 16:14
  • Add the link in normal WordPress post. I'd like to specify some sites in the code and add specific ID to each. – kacper3355 Mar 12 at 16:23
  • For example - when I add post containing example.com, my partner ID should be automatically added to the very end of this url – kacper3355 Mar 12 at 16:24
0

This is very simple to achieve with JavaScript. Place this at the bottom of your page, just before </body> tag.

This will append ?pp=my-affiliate-id at the end of your links. Just change the variable aid value below:

<script>
// Change "my-affiliate-id" below to your actual affiliate id
const aid = 'my-affiliate-id';

// Append slash with affiliate id, only if an affiliate ID is not found in the link yet
const goglinks = document.querySelectorAll('a[href*="gog.com"]');
goglinks.forEach(function(el) {
  if(!el.href.includes('pp=')) {
    el.href = el.href.replace(/\?.*$/, '') + '?pp=' + aid
  }
})
</script>

Demo: https://jsfiddle.net/samliew/ks3y8059

  • Two small caveats: first, somewhere you need to insure jQuery gets loaded (say, via wp_enqueue_script()); second, WordPress runs jQuery in compatibility mode, so the wrappings in the script tags need tweaking. – Loren Rosen Apr 1 at 0:45
  • @LorenRosen I've removed the dependancy on jQuery. Thanks for the feedback :) – Samuel Liew Apr 1 at 1:04
  • I think using jQuery here is quite reasonable. Only thing is, since we don't know OPs experience level, nor the level of any future readers, there's always the dilemma of how much to assume vs. how much to belabor what folks already know. – Loren Rosen Apr 1 at 1:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.