Black Friday & Cyber Monday SUPER SALE ALL WEEK:
Grab 40% OFF on plugins
Days
Hours
Minutes
Seconds

How to make WooCommerce external product links open in a new tab

An External or Affiliate product in WooCommerce cannot be directly bought from the website, and needs to be purchased from an external source to which it is linked.

How to make WooCommerce external product links open in a new tab - External Product Page Example
An external product page in WooCommerce

A common problem faced by WooCommerce users is that the link associated with the Add to Cart or Buy Product or Buy Now button of such a product opens in the same browser tab or window. This is a problem because it makes the user leave the site altogether, leading to not just bad business but also bad page ranking.  The bounce rate of a page relates to the number of times a user has left the page or website. A high bounce rate negatively impacts page ranking and thus is considered bad for SEO. Let’s find out how to make WooCommerce external product links open in a new tab or window.

You will need to change the behaviour of the Buy Product button in two places viz. the shop page and the product page.

How to make WooCommerce external product links open in a new tab - Shop Page
Shop Page

 

How to make WooCommerce external product links open in a new tab - Product Page
Product Page

The code snippet below takes care of the link associated with this button, on both these pages. Insert it into the functions.php file of your child theme.

  // This will take care of the Buy Product button below the external product on the Shop page.
 add_filter( 'woocommerce_loop_add_to_cart_link',  'ts_external_add_product_link' , 10, 2 );

  // Remove the default WooCommerce external product Buy Product button on the individual Product page.
 remove_action( 'woocommerce_external_add_to_cart', 'woocommerce_external_add_to_cart', 30 );

  // Add the open in a new browser tab WooCommerce external product Buy Product button.
 add_action( 'woocommerce_external_add_to_cart', 'ts_external_add_to_cart', 30 );

 
function ts_external_add_product_link( $link ) {
          global $product;

          if ( $product->is_type( 'external' ) ) {

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

          return $link;
 }

function ts_external_add_to_cart() {
                    global $product;

                    if ( ! $product->add_to_cart_url() ) {
                    return;
                    }

                    $product_url = $product->add_to_cart_url();
                    $button_text = $product->single_add_to_cart_text();

/**
 *  The code below outputs the edited button with target="_blank" added to the html markup.
 */
                    do_action( 'woocommerce_before_add_to_cart_button' ); ?>

                    <p class="cart">
                    <a href="<?php echo esc_url( $product_url ); ?>" rel="nofollow" class="single_add_to_cart_button                                                           button alt" target="_blank">  
                    <?php echo esc_html($button_text ); ?></a>
                    </p>

                    <?php do_action( 'woocommerce_after_add_to_cart_button' );

 }

Here, both the woocommerce_loop_add_to_cart_link and woocommerce_external_add_to_cart hooks have been used for the shop and product pages respectively. The difference between add_filter() and add_action() is that while the former is used to modify variable values in the existing function, the latter (add_action()) is used to replace the code in the function. The remove_action() function helps in unbinding the default function associated with the woocommerce_external_add_to_cart hook. This is necessary because the default function does the job of rendering the Buy Product button and if this default function is not unhooked, it will result in the button being rendered twice on the Product page, one will open the link in the same tab (as defined by the default function), and the other button (rendered by our function ts_external_add_to_cart) will open the link in a new tab.

Both the buttons (on the shop page and the product page) will now open the product in a new browser tab, thus ensuring that the user can return to the site whenever they want to, by switching the tab or window.

How to Make External Product Image and Title Open in a New Tab in WooCommerce?

We have already looked into offering a seamless browsing experience to your customers with this valuable functionality that allows WooCommerce external product links from the “Add to Cart” button to open in a new tab. However, when customers click the product title or image, they are redirected to an external site in the same tab, a common concern voiced by many store owners. This behavior can be frustrating, as it leads users away from your site, negatively impacting your SEO and overall visibility.

Don’t worry! We have a solution to make sure that external product image and title be opened in a new tab on the WooCommerce shop page. This way, you can have your site in place while letting customers to explore products from other sites which enhances their user experience. Let’s dive into the solution!

Solution: Make External Product Image and Title Open in a New Tab in WooCommerce

This code modifies the WooCommerce shop page to ensure that external product images and titles open in a new tab when clicked.

// Add External Product Link to Title and Image on the Shop Page
add_filter( 'woocommerce_product_get_image', 'ts_external_product_image_link', 10, 5 );
add_action( 'woocommerce_before_shop_loop_item_title', 'ts_external_product_title_link_open', 10 );
add_action( 'woocommerce_after_shop_loop_item_title', 'ts_external_product_title_link_close', 10 );

// Function to Add External Product Link to the Image
function ts_external_product_image_link( $image, $product_id, $size, $attr, $placeholder ) {
    $product = wc_get_product( $product_id );

    // Check if the product is an external product
    if ( $product && $product->is_type( 'external' ) ) {
        $image_link = $product->add_to_cart_url(); // Use the external URL for the image link
        $image = sprintf( '<a href="%s" target="_blank">%s</a>', esc_url( $image_link ), $image );
    }

    return $image;
}

// Function to Open the External Product Title Link
function ts_external_product_title_link_open() {
    global $product;

    // Check if the product is an external product
    if ( $product && $product->is_type( 'external' ) ) {
        $product_url = esc_url( $product->add_to_cart_url() ); // External URL
        echo '<a href="' . $product_url . '" target="_blank">';
    }
}

// Function to Close the External Product Title Link
function ts_external_product_title_link_close() {
    global $product;

    // Only close the link for external products
    if ( $product && $product->is_type( 'external' ) ) {
        echo '</a>';
    }
}

Output

Let’s consider a scenario where a customer clicks on the image of an external product. By default, this action opens the link in the same tab, which takes the customer away from your site. However, the code provided modifies this native behavior of WooCommerce, allowing the image link to open in a new tab. This means the customer is redirected to the external website without leaving your original site.

Checkout the video detailed walkthrough of the output.

How to Make ‘Add to Cart’ Button in WooCommerce Blocks to Open in a New Tab?

With the default WooCommerce behavior, there is a chance of losing customers when they click on external product links, as these links open in the same tab instead of a new one. This issue also occurs when using the new WooCommerce product blocks. In this post, we will address the issue of opening external or affiliate products in a new tab, especially when using the WooCommerce product blocks feature.

Solution: Make ‘Add to Cart’ Button in WooCommerce Blocks to Open in a New Tab

The provided code snippet works specifically for WooCommerce product blocks. It targets the affiliate product buttons and modifies their default behaviour so that when clicked, they open in a new tab.

// open External/Affiliate products in a new tab
function ts_open_affiliate_products_in_new_tab() {
    ?>
    <script type="text/javascript">
        document.addEventListener('DOMContentLoaded', function() {
            // Select all WooCommerce product items in the block
            document.querySelectorAll('.wc-block-product').forEach(function(product) {
                // Find the product link and button
                const affiliateLink = product.querySelector('a.product_type_external')?.href;
                const button = product.querySelector('.wc-block-components-product-button__button');
                
                // Log the product, affiliate link, and button for debugging
                console.log('Product:', product);
                console.log('Affiliate link:', affiliateLink);
                console.log('Button:', button);

                // Ensure we have an affiliate link and the button exists
                if (affiliateLink && button) {
                    button.addEventListener('click', function(e) {
                        e.preventDefault(); // Prevent the default form submission
                        console.log('Opening in new tab:', affiliateLink); // Log the link that will be opened
                        window.open(affiliateLink, '_blank'); // Open the affiliate link in a new tab
                    });
                }
            });
        });
    </script>
    <?php
}
add_action('wp_footer', 'ts_open_affiliate_products_in_new_tab');

Output

When customers click on an affiliate product button in your WooCommerce product blocks, the affiliate link will be opened in a new tab.

A significant step towards enhancing your customers’ shopping experience is encouraging them to create accounts before purchasing external products. One useful customization for this is: How to Require Customer Login Before Displaying β€˜Buy Now’ Button for WooCommerce External Products?

Browse more in: Code Snippets, WooCommerce How Tos, WooCommerce Tutorials

Share It:

49 thoughts on “How to make WooCommerce external product links open in a new tab

  1. The code you shared is almost correct but needs a bit of modification to ensure it properly handles both the shop page and the single product page for external products.

    I used this code using “Code Snippets” plugin.

    // Modify the Buy Now button for external products on the Shop page
    add_filter( ‘woocommerce_loop_add_to_cart_link’, ‘ts_external_add_product_link’ , 10, 2 );

    function ts_external_add_product_link( $link, $product ) {
    if ( $product->is_type( ‘external’ ) ) {
    $link = sprintf( ‘%s’,
    esc_url( $product->add_to_cart_url() ),
    esc_attr( isset( $quantity ) ? $quantity : 1 ),
    esc_attr( $product->get_id() ),
    esc_attr( $product->get_sku() ),
    esc_attr( ‘button product_type_external’ ),
    esc_html( $product->add_to_cart_text() )
    );
    }
    return $link;
    }

    // Remove the default Buy Now button for external products on the Single Product page
    remove_action( ‘woocommerce_external_add_to_cart’, ‘woocommerce_external_add_to_cart’, 30 );

    // Add custom Buy Now button with target=”_blank” for external products on the Single Product page
    add_action( ‘woocommerce_external_add_to_cart’, ‘ts_external_add_to_cart’, 30 );

    function ts_external_add_to_cart() {
    global $product;

    if ( ! $product->add_to_cart_url() ) {
    return;
    }

    $product_url = $product->add_to_cart_url();
    $button_text = $product->single_add_to_cart_text();

    /**
    * The following outputs the custom button with target=”_blank”.
    */
    do_action( ‘woocommerce_before_add_to_cart_button’ ); ?>

    <a href=”” rel=”nofollow” class=”single_add_to_cart_button button alt” target=”_blank”>

    <?php do_action( ‘woocommerce_after_add_to_cart_button’ );
    }

    1. Hi Vikas,

      Thank you for sharing your version of the code! You’re right that removing the extra attributes simplifies the button rendering for external product links. While they aren’t necessary for this specific use case, they don’t affect the functionality.

  2. Hello, I’ve added this code but it is breaking the default button style. How to stop it removing the button style from Buy now buttons?
    Here is myxample product page
    https://floridapsychics.org/shop/books/psychic-awakening-a-beginners-guide-to-developing-your-intuitive-psychic-abilities-including-clairvoyance-mind-reading-manifestation-astral-projection-mediumship-and-spirit-guides
    See the Buy Now button, it’s style is removed by your code.

  3. 1)After opening the Single Product page, the back button at the top left of the browser page is not taking me back to the Product listing/Shop page. It is going to the Home page. How to fix this issue?
    2) Also, how to open single product page in a new tab?

  4. Thank you so much! My Links were not working at all and I had already added 35 products! Then I found this post and I’m so happy I did. they now open in a new tab as they should! You saved my butt!

  5. Thanks!
    Worked perfectly for me.
    Also, I didnt have a child theme, but it worked at the main theme. Thank you.

  6. this doesnt’ work for me anymore.. i get this error

    Fatal error: Uncaught Error: Call to a member function is_type() on null in /wp-content/themes/efor-child/functions.php:25 
    
    

    can you please help πŸ™

  7. Thank you so much.
    It works perfectly on the WooCommerce Shop page and the Single Product Page. However, it doesn’t work for the products that I used WooCommerce Blocks.
    I’d like to make the WooCommerce Blocks’ β€˜Add to Cart’ button open a new tab on my front page. Would you please help me to figure this out?
    Thanks.

  8. Dose this also stop google following the link as i dont want google bots to my main shop website as it has products on it that google ads wont allow

  9. hello anubha,
    thank you for this suggestion, i have implemented but it doesnt work on my website. what could be the reason?
    thank you
    maria

    1. actually its working for the wishlist and products without variations. but in my shop there will be a lot of products with variations. can this be somehow solved? also the script overrides some css in the wishlist and it looks quite broken. how can i remocve this style?
      https://moebel-guru.com/produkt/veng-von-re-beds-bett-urbanara-edition-eiche-leinen-natur/
      https://moebel-guru.com/favoriten/ (the red button is the wrong style, the right one is the rext text)

  10. Hi,
    Very clever script thanks a lot. I have a quick question. Is it possible to force customer login/register before show “buy now” (external product link) button. I need to collect customer information before they open external link. regards

  11. This code works great. I just have an issue where it clashes with another plugin (affiliatehub). If I deactivate that plugin the code works perfect, but I need the plugin to update “external” pricing from other sites (such as amazon). When I put the code into the config file, I get the “buy now” button going to the same page link, but adds /undefined which cause a 404.
    If I remove the code, it works fine, but won’t open in new tag.
    I have a catch 22 here. I really want to open in new tab, but I also want the plugin to update pricing.
    Has anyone else run into this issue?

    What I have done so far.
    Created child theme.
    Played back and forth with the code
    Found the conflict, which is the plugin.

    Funny thing is that when I look at the page source, the code and href link seems perfectly fine, should work.. but doesn’t.

    Anyone with any suggestions?

  12. Hi Anubha,
    Thanks for this Great Tips ! I have the same question than Francisco. The external link is now on the button, it’s Very Great ( again πŸ™‚ but, is it possible to have the external link on the title and on the image too for the shop page not just on the button ? or if it’s not possible, can we unlink the link that there are on the image and on the title of the product ?
    Thanks a lot.

  13. Is it possible that even the pictura the text and de button of the product can they get open in an external link and nofollow?

    1. Hello Joao, it is designed to work on the Shop and Archive pages, not on the individual product page. This is because it is an external product, so the link on the product page needs to point to the website where it can be bought from.

  14. Hi Anubha,

    Thank you a lot for this useful post. It works very well.

    I want to ask, When we select an external product, How we can make this “Buy product” button displayed ONLY on a single product page AND NOT displayed on the Home page or on the Category page.

    Thank YoU.

    1. Hi David,

      Thank you for your comment.
      I will do a separate post on this in the next week and share the link with you here, if that’s okay πŸ™‚

      1. Hi Anubha, I would like to change the behavior of my woocommerce external buy now button to add to cart so that there is no redirect and items are added to my site cart for checkout. Thank you

  15. Thank you very much, I had tried almost everything and nothing worked. Your solution works perfectly, but in each individual product duplicates the buy button. What can I Do?

    1. Problem solved, I had a plugin that was drawing me the other button. Thank you very much blessings.

        1. “Problem solved, I had a plugin that was drawing me the other button. Thank you very much blessings.”

          Hello, do you know whats causing this issue.

Leave a Reply to David Cancel reply

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

Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible.

Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

By using our site, you acknowledge that you have read and understood our Privacy Policy and Terms & Conditions.