# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [WooCommerce](https://wpide.com/library/category/woocommerce/)
- Requires: WooCommerce
- Tags: woocommerce, affiliate, external, links
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/woo-external-products-new-tab/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Open External/Affiliate Product Links in a New Tab" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
