Last active
October 8, 2019 21:00
-
-
Save petertwise/1a88ac87ec3e965c61f41208f93c6b8e to your computer and use it in GitHub Desktop.
Add Amazon affiliate tag to all Amazon links in WordPress the_content
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// This adds a hard coded Amazon affiliate tag to all amazon links in the_content | |
// Code adapted from the abandoned "Amazon Affiliate Tag" plugin | |
// https://wordpress.org/plugins/amazify/ by Maxime Bridon https://bridon.fr/ | |
function add_amazon_tag( $content ) { | |
// the affiliate tag for Peter Bregman | |
$affiliate_tag = 'yourtaghere-123'; | |
// regex to find any link | |
$link_regex = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>"; | |
// regex to find amazon urls | |
$amazon_regex = "(.*)amazon\.(com|co.uk|de|fr|co.jp|ca)+"; | |
// find all the links | |
if ( preg_match_all( "/$link_regex/siU", $content, $link_matches, PREG_SET_ORDER ) ) { | |
// loop through the links | |
foreach ($link_matches as $match) { | |
// if it is an Amazon link... | |
if ( preg_match( "/$amazon_regex/i", $match[2] ) ) { | |
// get the URL of the amazon link, parse it into component parts | |
$thelink = str_replace('&', "&", $match[2]); | |
$parsed = parse_url($thelink); | |
if ( isset( $parsed['query'] ) && preg_match( '#tag#i', $parsed['query'] ) ) { | |
// if the link has a tag already, replace it | |
$query_string = html_entity_decode($parsed['query']); | |
parse_str($query_string, $variables); | |
$variables["tag"] = $affiliate_tag; | |
$new_query = http_build_query($variables, '', '&'); | |
$newlink = '<a href="'.$parsed['scheme'].'://'.$parsed['host'].$parsed['path'].'?'.$new_query.'">'.$match[3].'</a>'; | |
} elseif ( isset($parsed['query'] ) ) { | |
// or if the link has a query string, but no tag - append our tag to the query | |
$newlink = '<a href="'.$thelink.'&tag='.$affiliate_tag.'">'.$match[3].'</a>'; | |
} else { | |
// otherwise, the link has no tag or query - just add our tag as a new query | |
$newlink = '<a href="'.$thelink.'?tag='.$affiliate_tag.'">'.$match[3].'</a>'; | |
} | |
// replace the old link with the newly contstructed one | |
$content = str_replace($match[0], $newlink, $content); | |
} | |
} | |
} | |
return $content; | |
} | |
add_filter('the_content', 'add_amazon_tag'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment