WooCommerce: Open external/affiliate products in a new tab (shop page)

By default, all WooCommerce external/affiliate products open up in the very same tab, but what if you’d like to have all your external/affiliate type products open up in a new tab, from the shop/archive page? Well, then the code below will do just that

add_filter( 'woocommerce_loop_add_to_cart_link', 'add_target_blank', 10, 2 );
 
function add_target_blank( $link, $product ){

	if ( 'external' === $product->get_type() ) { 

$link = sprintf( '<a href="%s" target="_blank" rel="nofollow" data-product_id="%s" data-product_sku="%s" data-quantity="%s" class="button product_type_%s">%s</a>',
        esc_url( $product->add_to_cart_url() ),
        esc_attr( $product->get_id() ),
        esc_attr( $product->get_sku() ),
        esc_attr( isset( $quantity ) ? $quantity : 1 ),
        esc_attr( $product->get_type() ),
        esc_html( $product->add_to_cart_text() )
);
	}
return $link;
}


Was this helpful? Please buy me a coffee






This code should be added to your child theme’s functions.php file or via a plugin that allows custom functions to be added, such as the Code snippets plugin. Please don’t add custom code directly to your parent theme’s functions.php file as this will be wiped entirely when you update.

Share your thoughts

Your email address will not be published. Required fields are marked *