Last active
January 18, 2019 18:20
-
-
Save adamcapriola/d0c04093ec3357da6c045ae442de9320 to your computer and use it in GitHub Desktop.
Auto-tag Amazon.com links (v2: Clean)
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 | |
/** | |
* Auto-tag Amazon.com links (v2: Clean) | |
* | |
*/ | |
add_filter( 'the_content', 'ac_auto_tag_amazon_links_v2' ); | |
function ac_auto_tag_amazon_links_v2( $content ) { | |
// Variables | |
$amazon_tag = array( 'tag' => 'adamcapr-20', ); // Update with your tracking ID | |
// Reconstruct /dp/ASIN URLs to remove all extraneous strings and parameters; add tag to URLs | |
// Find all Amazon URLs | |
preg_match_all( '/a href="(https?:\/\/(?:www)?\.amazon\.com[^"]*)"/', $content, $matches ); | |
// Find all /dp/ASINs | |
$asins = array(); | |
foreach ( $matches[1] as $amazon_url ) { | |
preg_match( '/(?:\/dp\/([A-Z0-9]{10}))/', $amazon_url, $asins[] ); | |
} | |
foreach ( $asins as $asin ) { | |
$matches[2][] = ( isset( $asin[1] ) ) ? $asin[1] : ''; | |
} | |
// Reconstruct URLs | |
$search_urls = $replace_urls = array(); | |
foreach ( $matches[1] as $key => $amazon_url ) { | |
// Search URLs | |
$search_urls[] = $amazon_url; | |
// Replace URLs: No /dp/ASIN | |
if ( empty( $matches[2][ $key ] ) ) { | |
$replace_urls[] = add_query_arg( $amazon_tag, $amazon_url ); | |
} | |
// Replace URLs: /dp/ASIN | |
else { | |
$replace_urls[] = add_query_arg( $amazon_tag, 'https://www.amazon.com/dp/' . $matches[2][ $key ] . '/' ); | |
} | |
} | |
// preg_replace | |
foreach ( $search_urls as $key => $search_url ) { | |
$content = preg_replace( '/a href="' . preg_quote( $search_url, '/' ) . '"/', 'a href="' . esc_url( $replace_urls[ $key ] ) . '"', $content ); | |
} | |
return $content; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment