Open External/Affiliate Product Links in a New Tab
Makes the buy buttons of external (affiliate) products open the partner site in a new tab, on shop pages and on the product page.
Opens WPIDE on
Code
add_filter( 'woocommerce_loop_add_to_cart_link', function ( $html, $product ) {
if ( $product->is_type( 'external' ) && false === strpos( $html, 'target=' ) ) {
$html = str_replace( '<a ', '<a target="_blank" rel="noopener sponsored" ', $html );
}
return $html;
}, 10, 2 );
add_action( 'woocommerce_after_add_to_cart_form', function () {
global $product;
if ( ! $product instanceof WC_Product || ! $product->is_type( 'external' ) ) {
return;
}
echo "<script>document.querySelectorAll('form.cart').forEach(function(f){ if (f.getAttribute('method') === 'get') { f.setAttribute('target', '_blank'); f.setAttribute('rel', 'noopener sponsored'); } });</script>\n";
} );
Notes
Adds rel="noopener sponsored" to the links, which is recommended for affiliate links.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.