Skip to content

Instantly share code, notes, and snippets.

@R3V1Z3
Last active December 17, 2015 16:49
Show Gist options
  • Save R3V1Z3/5641630 to your computer and use it in GitHub Desktop.
Save R3V1Z3/5641630 to your computer and use it in GitHub Desktop.
WordPress shortcode to easily link to Amazon search results with associate id. Includes security considerations as well as defaults to make it as simple as possible to use.
<?php
// Shortcode to easily link to Amazon search results with associate id.
// Use:
// [amazon-search search="WordPress"]WordPress[/amazon-search]
// [amazon-search search="WordPress"]
// [amazon-search search="WordPress" id="my-id"]WordPress Search on Amazon[/amazon-search]
function ugotsta_amazon_search_shortcode($search, $content = null ) {
// get attributes
extract(shortcode_atts(array(
'search' => 'flying+screaming+monkey',
'id' => 'ugotsta-20'
), $search));
// escape the attributes for security purposes
$id = esc_attr($id);
$search = esc_attr($search);
// set default content if none is provided
if ( is_null($content) || empty($content) ) {
// set default content if no content or search string provided
if ( is_null($search) || empty($search) ) {
$content = 'LINK';
} else {
// set default content to search string if provided
$content = $search;
}
}
// escape $content for security purposes
$content = esc_attr($content);
// convert $search to lowercase
$search = strtolower($search);
// convert whitespaces and underscore to plus
$search = preg_replace("/[\s_]/", "+", $search);
// setup variables for return string
$amazon_search_url = 'http://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=';
// setup link url
$amazon_search_url = $amazon_search_url . $search . '&amp;tag=' . $id;
// return full link
return '<a href="' . $amazon_search_url . '" target="_blank">' . $content . '</a>';
}
add_shortcode('amazon-search', 'ugotsta_amazon_search_shortcode');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment