Created
April 8, 2022 14:01
-
-
Save renventura/ea150a02d82defa1bcf3753e115cf29b to your computer and use it in GitHub Desktop.
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 | |
add_filter( 'the_content', 'add_rel_sponsored_affiliate_links' ); | |
/** | |
* Add rel="sponsored" to external affiliate links in WordPress. | |
* Affiliate links should be distinguishable through some kind of unique prefix. | |
* | |
* @param string $content Post content | |
* | |
* @return string | |
*/ | |
function add_rel_sponsored_affiliate_links( $content ) { | |
$dom = new DOMDocument(); | |
/** | |
* Prepend "<?xml encoding="utf-8" ?>"" to avoid issues with UTF-8 string interpretation | |
*/ | |
@$dom->loadHTML( '<?xml encoding="utf-8" ?>' . $content ); | |
$links = $dom->getElementsByTagName( 'a' ); | |
$links_replaced = false; | |
foreach ( $links as $link ) { | |
// Check for our affiliate links | |
// Affiliate links are prepended with /go/ | |
$href = $link->getAttribute( 'href' ); | |
// Skip if not an affiliate link | |
if ( false === strpos( $href, '/go/' ) ) { | |
continue; | |
} | |
// Add in the rel="sponsored" attribute | |
$links_replaced = true; | |
$rel = $link->getAttribute( 'rel' ); | |
$link->setAttribute( 'rel', $rel . ' ' . 'sponsored' ); | |
} | |
// Save the HTML | |
if ( $links_replaced ) { | |
$content = $dom->saveHTML(); | |
} | |
return $content; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment