My Home on the Web. Where the Code Snippets Run Free.

Amazon Affiliate Shortcode for WordPress

Amazon Affiliate Shortcode for WordPress

I love programming. I love the problem solving and the “I did that!” moment when you see what you wrote come to life. I’m also kind of lazy and get bored easily. I love creating life automators.

I recently signed up for the Amazon Affiliate program and found myself embedding links into posts and pages on a regular basis. If you are familiar with the program, the format is pretty straight forward:
http://www.amazon.com/dp/asin_or_isbn/dp/?tag=affiliate_code
Replace the asin_or_isbn placeholder with the product’s ASIN, or the book’s 10-digit ISBN. Then, replace the affiliate_code placeholder with your Amazon assigned code. Or, just use your affiliate code and link to generic pages, such as the Amazon home page:
http://www.amazon.com/?tag=affiliate_code

That, folks, looks to me like a bunch of repetition!
Why we don’t like repetition:

  • It’s time-consuming to type over and over
  • It’s prone to typing mistakes
  • What happens if the format changes? You’ll need to update the links manually (yuck!).

WordPress makes creating shortcodes really easy. Here is my simple affiliate automation shortcode:

What does all that do?

The shortcode accepts three attributions:

text
This is the anchor text that will appear in the anchor link. If this is left blank, no link would appear. Therefore, the first if statement advises by outputting an error condition in lieu of the link.
isbn
The product ASIN or book’s 10-digit ISBN. If this is left blank, the affiliate link will default to Amazon’s home page
affiliate
The affiliate link that will be applied to the link. If no attribute is provided in the shortcode, the default value can be assigned (in my case, chrisbarrettc-20)

Input and Output

Once you have created and added the function to your custom child theme, here are how different argument combinations will be handled:

Simply Link to the Amazon Home Page:

[amazon text="Click Here for the Amazon Homepage"]

Click Here for the Amazon Homepage

Amazon Product Link using the Default Affiliate:

[amazon isbn="0345404475" text="Do Androids Dream of Electric Sheep?"]

Do Androids Dream of Electric Sheep?

Amazon Product Link using a Custom Affiliate:

[amazon isbn="0345404475" text="Do Androids Dream of Electric Sheep?" affiliate="your-name-here"]

An Empty or Missing text Attribute Warning:

[amazon isbn="0345404475" affiliate="chrisbarrettc-20"]
"text" cannot be blank

Interested in learning more about the Amazon Affiliate program? Learn More Here

2 Comments
  1. This is really a great tip.
    I changed the code to handle locale as well
    Thanks for idea.

    • You’re welcome. Happy to hear you found the post useful!

      Cheers!
      Chris