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

How to Add External Links for Each Variations and Open it in New Tab for WooCommerce Variable Products?

Have you ever wanted to turn your WooCommerce variable products into affiliate items with specific external links for each variation? While you can easily designate a product as an external or affiliate type by selecting “External/Affiliate” product type. But this method only allows for a single URL.

In this post, we address the limitation for variable products that require different URLs for each variation. The code creates a distinct URL field for each product variation in the edit product section, enabling store owners to set unique external links that open in a new tab after the customer chooses the variation and clicks the ‘Add to Cart’ button. By implementing this solution, you can enhance the shopping experience for your customers while maximizing your affiliate potential for variable products as well.

Solution: Add External Links for Each Variations and Open it in New Tab for WooCommerce Variable Products

The code will adds the text URL field for each variations in the edit product page at the backend.
If an url is entered for the variation, the value gets saved. On the product page when customers select a variation and click on ‘Add to cart’, the external link will be opened in new tab.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// Add External URL Field to Product Variations
add_action('woocommerce_variation_options', 'ts_add_external_url_field', 10, 3);
function ts_add_external_url_field($loop, $variation_data, $variation) {
woocommerce_wp_text_input(array(
'id' => "external_url_{$variation->ID}",
'name' => "external_url_{$variation->ID}",
'label' => __('External URL', 'woocommerce'),
'placeholder' => 'https://example.com',
// 'description' => __('Enter an external URL for this variation.', 'woocommerce'),
'value' => get_post_meta($variation->ID, '_external_url', true),
));
}
// Save External URL Field Value
add_action('woocommerce_save_product_variation', 'ts_save_external_url_field', 10, 2);
function ts_save_external_url_field($variation_id, $i) {
$external_url = isset($_POST["external_url_{$variation_id}"]) ? $_POST["external_url_{$variation_id}"] : '';
update_post_meta($variation_id, '_external_url', esc_url($external_url));
}
// Pass External URL to the Frontend
add_filter('woocommerce_available_variation', 'ts_add_external_url_to_variation');
function ts_add_external_url_to_variation($variation_data) {
$external_url = get_post_meta($variation_data['variation_id'], '_external_url', true);
if ($external_url) {
$variation_data['external_url'] = $external_url; // Add the external URL to the variation data
}
return $variation_data;
}
// JavaScript to handle "Add to Cart" click for external URL
add_action('wp_footer', 'ts_add_custom_js');
function ts_add_custom_js() {
if (is_product()) {
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
// When the Add to Cart button is clicked
$('form.cart').on('submit', function(event) {
event.preventDefault(); // Prevent the default form submission
// Get selected variation data
var variation_id = $('input[name="variation_id"]').val();
var variation = $('form.variations_form').data('product_variations').find(function(variation) {
return variation.variation_id == variation_id;
});
// Check if the external URL exists
if (variation && variation.external_url) {
// Open the external URL in a new tab
window.open(variation.external_url, '_blank');
} else {
// Submit the form normally if no external URL is found
$(this).off('submit').submit();
}
});
});
</script>
<?php
}
}
// Add External URL Field to Product Variations add_action('woocommerce_variation_options', 'ts_add_external_url_field', 10, 3); function ts_add_external_url_field($loop, $variation_data, $variation) { woocommerce_wp_text_input(array( 'id' => "external_url_{$variation->ID}", 'name' => "external_url_{$variation->ID}", 'label' => __('External URL', 'woocommerce'), 'placeholder' => 'https://example.com', // 'description' => __('Enter an external URL for this variation.', 'woocommerce'), 'value' => get_post_meta($variation->ID, '_external_url', true), )); } // Save External URL Field Value add_action('woocommerce_save_product_variation', 'ts_save_external_url_field', 10, 2); function ts_save_external_url_field($variation_id, $i) { $external_url = isset($_POST["external_url_{$variation_id}"]) ? $_POST["external_url_{$variation_id}"] : ''; update_post_meta($variation_id, '_external_url', esc_url($external_url)); } // Pass External URL to the Frontend add_filter('woocommerce_available_variation', 'ts_add_external_url_to_variation'); function ts_add_external_url_to_variation($variation_data) { $external_url = get_post_meta($variation_data['variation_id'], '_external_url', true); if ($external_url) { $variation_data['external_url'] = $external_url; // Add the external URL to the variation data } return $variation_data; } // JavaScript to handle "Add to Cart" click for external URL add_action('wp_footer', 'ts_add_custom_js'); function ts_add_custom_js() { if (is_product()) { ?> <script type="text/javascript"> jQuery(document).ready(function($) { // When the Add to Cart button is clicked $('form.cart').on('submit', function(event) { event.preventDefault(); // Prevent the default form submission // Get selected variation data var variation_id = $('input[name="variation_id"]').val(); var variation = $('form.variations_form').data('product_variations').find(function(variation) { return variation.variation_id == variation_id; }); // Check if the external URL exists if (variation && variation.external_url) { // Open the external URL in a new tab window.open(variation.external_url, '_blank'); } else { // Submit the form normally if no external URL is found $(this).off('submit').submit(); } }); }); </script> <?php } }
// Add External URL Field to Product Variations
add_action('woocommerce_variation_options', 'ts_add_external_url_field', 10, 3);
function ts_add_external_url_field($loop, $variation_data, $variation) {
    woocommerce_wp_text_input(array(
        'id' => "external_url_{$variation->ID}",
        'name' => "external_url_{$variation->ID}",
        'label' => __('External URL', 'woocommerce'),
        'placeholder' => 'https://example.com',
        // 'description' => __('Enter an external URL for this variation.', 'woocommerce'),
        'value' => get_post_meta($variation->ID, '_external_url', true),
    ));
}

// Save External URL Field Value
add_action('woocommerce_save_product_variation', 'ts_save_external_url_field', 10, 2);
function ts_save_external_url_field($variation_id, $i) {
    $external_url = isset($_POST["external_url_{$variation_id}"]) ? $_POST["external_url_{$variation_id}"] : '';
    update_post_meta($variation_id, '_external_url', esc_url($external_url));
}

// Pass External URL to the Frontend
add_filter('woocommerce_available_variation', 'ts_add_external_url_to_variation');
function ts_add_external_url_to_variation($variation_data) {
    $external_url = get_post_meta($variation_data['variation_id'], '_external_url', true);
    if ($external_url) {
        $variation_data['external_url'] = $external_url; // Add the external URL to the variation data
    }
    return $variation_data;
}

// JavaScript to handle "Add to Cart" click for external URL
add_action('wp_footer', 'ts_add_custom_js');
function ts_add_custom_js() {
    if (is_product()) {
        ?>
        <script type="text/javascript">
        jQuery(document).ready(function($) {
            // When the Add to Cart button is clicked
            $('form.cart').on('submit', function(event) {
                event.preventDefault(); // Prevent the default form submission
                
                // Get selected variation data
                var variation_id = $('input[name="variation_id"]').val();
                var variation = $('form.variations_form').data('product_variations').find(function(variation) {
                    return variation.variation_id == variation_id;
                });
                
                // Check if the external URL exists
                if (variation && variation.external_url) {
                    // Open the external URL in a new tab
                    window.open(variation.external_url, '_blank');
                } else {
                    // Submit the form normally if no external URL is found
                    $(this).off('submit').submit();
                }
            });
        });
        </script>
        <?php
    }
}

Output

The code will add a new text field on the admin edit product page which allows store owners to set an external url for product variations as shown in the image below.

WooCommerce Variable Products

When customers clicks on the ‘Add to cart’ button associated with the variable product, they will be redirected to the specified external link in a new tab instead of being directed to the cart page of your site.

Add External Links and Open it in New Tab for WooCommerce Variable Products
How to Add External Links for Each Variations  for WooCommerce Variable Products?

Solution: Redirect Add to Cart in Quick View Modal in OceanWP Theme to External URLs

While the external redirection works seamlessly on the product page, we’ll now look at how to make it work inside the Quick View pop-up modal as well. One of our clients requested this feature, wanting the same external link behavior to function within the Quick View modal offered by the popular OceanWP theme. This acts as a key requirement for affiliate setups where each variation links to platforms like Amazon or other external sites.

Replace your previous code with the following to handle both product page and quick view modal functionality offered in the OceanWP theme.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// 1. Add external URL field to each variation in admin
add_action('woocommerce_variation_options', 'ts_add_external_url_field', 10, 3);
function ts_add_external_url_field($loop, $variation_data, $variation) {
woocommerce_wp_text_input(array(
'id' => "external_url_{$variation->ID}",
'name' => "external_url_{$variation->ID}",
'label' => __('External URL', 'woocommerce'),
'placeholder' => 'https://example.com',
'value' => get_post_meta($variation->ID, '_external_url', true),
));
}
// 2. Save external URL field
add_action('woocommerce_save_product_variation', 'ts_save_external_url_field', 10, 2);
function ts_save_external_url_field($variation_id, $i) {
$external_url = isset($_POST["external_url_{$variation_id}"]) ? $_POST["external_url_{$variation_id}"] : '';
update_post_meta($variation_id, '_external_url', esc_url($external_url));
}
// 3. Add external URL to variation data
add_filter('woocommerce_available_variation', 'ts_add_external_url_to_variation');
function ts_add_external_url_to_variation($variation_data) {
$external_url = get_post_meta($variation_data['variation_id'], '_external_url', true);
if ($external_url) {
$variation_data['external_url'] = $external_url;
}
return $variation_data;
}
// 4. Inject variation data into Quick View modal if needed
add_filter('ocean_woo_quick_view_product_content', 'ts_inject_variations_into_modal', 5);
function ts_inject_variations_into_modal() {
global $product;
if (!$product || !$product->is_type('variable')) {
return;
}
$variations = $product->get_available_variations();
$variations_json = wp_json_encode($variations);
echo '<script type="text/javascript">
jQuery(document).ready(function($) {
$(".quick-view-wrap form.variations_form").data("product_variations", ' . $variations_json . ');
});
</script>';
}
// 5. Script to redirect on external URL + update button text
add_action('wp_footer', 'ts_external_url_redirect_and_button_text', 99);
function ts_external_url_redirect_and_button_text() {
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
function getVariationFromForm($form) {
let variationId = $form.find('input[name="variation_id"]').val();
let variations = $form.data('product_variations');
if (!variations && $form.find('script.variations_json').length) {
try {
variations = JSON.parse($form.find('script.variations_json').html());
} catch (e) {
variations = null;
}
}
if (!variations || !variationId) return null;
return variations.find(v => v.variation_id == variationId);
}
// Update button text dynamically
function updateButtonText($form) {
const $button = $form.find('button.single_add_to_cart_button');
const variation = getVariationFromForm($form);
if (!variation) return;
if (variation.external_url) {
$button.text('Go to Amazon');
} else {
$button.text('Add to cart');
}
}
// Variation found or changed
$(document).on('found_variation', 'form.variations_form', function() {
updateButtonText($(this));
});
$(document).on('change', 'form.variations_form .variations select', function() {
const $form = $(this).closest('form.variations_form');
setTimeout(function() {
updateButtonText($form);
}, 100);
});
// Handle Add to Cart button click (redirect)
$(document).on('click', 'form.variations_form.cart button.single_add_to_cart_button', function(e) {
const $form = $(this).closest('form.variations_form');
const variation = getVariationFromForm($form);
if (variation && variation.external_url) {
e.preventDefault();
// Close modal if it's open
if ($('#owp-qv-wrap').is(':visible')) {
$('#owp-qv-wrap').fadeOut();
$('body').removeClass('owp-qv-open');
}
window.open(variation.external_url, '_blank');
return false;
}
});
});
</script>
<?php
}
// 1. Add external URL field to each variation in admin add_action('woocommerce_variation_options', 'ts_add_external_url_field', 10, 3); function ts_add_external_url_field($loop, $variation_data, $variation) { woocommerce_wp_text_input(array( 'id' => "external_url_{$variation->ID}", 'name' => "external_url_{$variation->ID}", 'label' => __('External URL', 'woocommerce'), 'placeholder' => 'https://example.com', 'value' => get_post_meta($variation->ID, '_external_url', true), )); } // 2. Save external URL field add_action('woocommerce_save_product_variation', 'ts_save_external_url_field', 10, 2); function ts_save_external_url_field($variation_id, $i) { $external_url = isset($_POST["external_url_{$variation_id}"]) ? $_POST["external_url_{$variation_id}"] : ''; update_post_meta($variation_id, '_external_url', esc_url($external_url)); } // 3. Add external URL to variation data add_filter('woocommerce_available_variation', 'ts_add_external_url_to_variation'); function ts_add_external_url_to_variation($variation_data) { $external_url = get_post_meta($variation_data['variation_id'], '_external_url', true); if ($external_url) { $variation_data['external_url'] = $external_url; } return $variation_data; } // 4. Inject variation data into Quick View modal if needed add_filter('ocean_woo_quick_view_product_content', 'ts_inject_variations_into_modal', 5); function ts_inject_variations_into_modal() { global $product; if (!$product || !$product->is_type('variable')) { return; } $variations = $product->get_available_variations(); $variations_json = wp_json_encode($variations); echo '<script type="text/javascript"> jQuery(document).ready(function($) { $(".quick-view-wrap form.variations_form").data("product_variations", ' . $variations_json . '); }); </script>'; } // 5. Script to redirect on external URL + update button text add_action('wp_footer', 'ts_external_url_redirect_and_button_text', 99); function ts_external_url_redirect_and_button_text() { ?> <script type="text/javascript"> jQuery(document).ready(function($) { function getVariationFromForm($form) { let variationId = $form.find('input[name="variation_id"]').val(); let variations = $form.data('product_variations'); if (!variations && $form.find('script.variations_json').length) { try { variations = JSON.parse($form.find('script.variations_json').html()); } catch (e) { variations = null; } } if (!variations || !variationId) return null; return variations.find(v => v.variation_id == variationId); } // Update button text dynamically function updateButtonText($form) { const $button = $form.find('button.single_add_to_cart_button'); const variation = getVariationFromForm($form); if (!variation) return; if (variation.external_url) { $button.text('Go to Amazon'); } else { $button.text('Add to cart'); } } // Variation found or changed $(document).on('found_variation', 'form.variations_form', function() { updateButtonText($(this)); }); $(document).on('change', 'form.variations_form .variations select', function() { const $form = $(this).closest('form.variations_form'); setTimeout(function() { updateButtonText($form); }, 100); }); // Handle Add to Cart button click (redirect) $(document).on('click', 'form.variations_form.cart button.single_add_to_cart_button', function(e) { const $form = $(this).closest('form.variations_form'); const variation = getVariationFromForm($form); if (variation && variation.external_url) { e.preventDefault(); // Close modal if it's open if ($('#owp-qv-wrap').is(':visible')) { $('#owp-qv-wrap').fadeOut(); $('body').removeClass('owp-qv-open'); } window.open(variation.external_url, '_blank'); return false; } }); }); </script> <?php }
// 1. Add external URL field to each variation in admin
add_action('woocommerce_variation_options', 'ts_add_external_url_field', 10, 3);
function ts_add_external_url_field($loop, $variation_data, $variation) {
    woocommerce_wp_text_input(array(
        'id' => "external_url_{$variation->ID}",
        'name' => "external_url_{$variation->ID}",
        'label' => __('External URL', 'woocommerce'),
        'placeholder' => 'https://example.com',
        'value' => get_post_meta($variation->ID, '_external_url', true),
    ));
}

// 2. Save external URL field
add_action('woocommerce_save_product_variation', 'ts_save_external_url_field', 10, 2);
function ts_save_external_url_field($variation_id, $i) {
    $external_url = isset($_POST["external_url_{$variation_id}"]) ? $_POST["external_url_{$variation_id}"] : '';
    update_post_meta($variation_id, '_external_url', esc_url($external_url));
}

// 3. Add external URL to variation data
add_filter('woocommerce_available_variation', 'ts_add_external_url_to_variation');
function ts_add_external_url_to_variation($variation_data) {
    $external_url = get_post_meta($variation_data['variation_id'], '_external_url', true);
    if ($external_url) {
        $variation_data['external_url'] = $external_url;
    }
    return $variation_data;
}

// 4. Inject variation data into Quick View modal if needed
add_filter('ocean_woo_quick_view_product_content', 'ts_inject_variations_into_modal', 5);
function ts_inject_variations_into_modal() {
    global $product;

    if (!$product || !$product->is_type('variable')) {
        return;
    }

    $variations = $product->get_available_variations();
    $variations_json = wp_json_encode($variations);

    echo '<script type="text/javascript">
        jQuery(document).ready(function($) {
            $(".quick-view-wrap form.variations_form").data("product_variations", ' . $variations_json . ');
        });
    </script>';
}

// 5. Script to redirect on external URL + update button text
add_action('wp_footer', 'ts_external_url_redirect_and_button_text', 99);
function ts_external_url_redirect_and_button_text() {
    ?>
    <script type="text/javascript">
    jQuery(document).ready(function($) {
        function getVariationFromForm($form) {
            let variationId = $form.find('input[name="variation_id"]').val();
            let variations = $form.data('product_variations');

            if (!variations && $form.find('script.variations_json').length) {
                try {
                    variations = JSON.parse($form.find('script.variations_json').html());
                } catch (e) {
                    variations = null;
                }
            }

            if (!variations || !variationId) return null;
            return variations.find(v => v.variation_id == variationId);
        }

        // Update button text dynamically
        function updateButtonText($form) {
            const $button = $form.find('button.single_add_to_cart_button');
            const variation = getVariationFromForm($form);
            if (!variation) return;

            if (variation.external_url) {
                $button.text('Go to Amazon');
            } else {
                $button.text('Add to cart');
            }
        }

        // Variation found or changed
        $(document).on('found_variation', 'form.variations_form', function() {
            updateButtonText($(this));
        });

        $(document).on('change', 'form.variations_form .variations select', function() {
            const $form = $(this).closest('form.variations_form');
            setTimeout(function() {
                updateButtonText($form);
            }, 100);
        });

        // Handle Add to Cart button click (redirect)
        $(document).on('click', 'form.variations_form.cart button.single_add_to_cart_button', function(e) {
            const $form = $(this).closest('form.variations_form');
            const variation = getVariationFromForm($form);

            if (variation && variation.external_url) {
                e.preventDefault();

                // Close modal if it's open
                if ($('#owp-qv-wrap').is(':visible')) {
                    $('#owp-qv-wrap').fadeOut();
                    $('body').removeClass('owp-qv-open');
                }

                window.open(variation.external_url, '_blank');
                return false;
            }
        });
    });
    </script>
    <?php
}

Output

When a customer visits the product page or uses the Quick View popup, and picks a variation, clicking the Add to Cart button will take them to the external link you’ve set (like an Amazon Kindle page).

Redirect Add to Cart in Quick View Modal in OceanWP Theme to External URLs

We hope you’ve successfully added unique external links for each variation of your products, as this paves the way to increase your affiliate potential. Additionally, consider applying this strategy to make WooCommerce external products, images, and titles open in a new tab . By doing so, you create a smoother browsing experience for your customers, which can lead to increased satisfaction and retention. Plus, minimizing bounce rates can positively impact your site’s SEO, helping you attract more visitors over time.

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

Share It:

Subscribe
Notify of


17 Comments
Newest
Oldest
Inline Feedbacks
View all comments
Anita
19 days ago

Hi Saranya,
Awesome code, thanks a ton. For ages I was looking for a way to add my Kindle books to my shop. On product page it’s working fine but not on quick view modal. The button isn’t changing from add to cart to the custom button (buy at Amazon). It’s adding the external product to the cart. Any idea? Thank you!

Anita
18 days ago
Reply to  Saranya

Thanks a lot for the quick reply! I’m using OceanWP theme with integrated quick view modal.
The standard variation is not marked plus the variations with external url use the add to cart button, not custom external button

Last edited 18 days ago by Anita
6 months ago

Where do I have to upload the code? Thank you

Shane
8 months ago

Hi Great bit of code.

I was a bit confused that on my site it actually added the items to the cart on my site as well as redirected me to the link, is that supposed to happen or have I misunderstood something?

8 months ago

Thank you so much for this. Much needed and appreciated. Is it possible to add a field for an optional button text for each variation? i.e. buy “buy at partnersite.com” 

Also compatibility with WPC Variation Bulk Editor for WooCommerce? This would allow setting many many links at once and save a ton of time.

8 months ago
Reply to  Saranya

Thank you, Saranya! You are amazing!!

I will reach out to WPC Variation Bulk Editor. Do you know of any other bulk editing plugin that might be compatible with the external URL field for the variations? Some of my products have 300 variations.

8 months ago
Reply to  Paul

Found a plugin that will allow me to bulk edit the variations’ external URL and button text fields using the _external_url and _button_text from your snippet 🙂

Plugin: Admin Columns – https://www.admincolumns.com/

Screenshot: https://share.zight.com/geuKK9g4

8 months ago
Reply to  Saranya

Unfortunately trying bulk edit too many variations at once using the Admin Columns plugin results in the custom fields being populated with URL and button text in the product backend and the button text showing on the front end but the products still end up in the cart when clicking 🙁

Now the fields are populated but it doesn’t work. Scratching my head. Definitely a database issue.

8 months ago
Reply to  Saranya

Hi Saranya,

Thank you again. You are amazing!

I am worried the problem is more with my database or theme. When there are too many variations in a product the external link is not triggered and the variation is added to the cart regardless of how I added the link to the custom field (bulk editor or normal entry). I am not sure what the threshold is for the # of variations is for when it stops working.

Sample URL where it doesn’t work: https://deathwaiver.com/product/ten-thousand-interval-short/

8 months ago
Reply to  Saranya

Hi Saranya, Thank you again for your amazing help! I was having problems with products that had many variations and the external URL would not work. The product was still added to the cart. I don’t think this was related to bulk editor as the URL was present regardless of how it was added (bulk or individually). Chat GPT modified the code somewhat and now it seems to work consistently!! Your code may need to be modified somewhat to address products with many variations. Maybe a site’s server or hosting specs has something to do with it? Anyway here is… Read more »

17
0
Would love your thoughts, please comment.x
()
x
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.