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.
$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');
functionts_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.
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.
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
// 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).
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.
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!
Hi Anita, I’m really glad to hear the solution worked on the main product page. To help resolve the issue with the Quick View popup modal, could you please provide some additional details, like whether you are using any plugin or a theme feature for the Quick View modal? This will help me replicate your setup and suggest the right fix.
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
Hi Anita, We’ve worked on a solution based on your requirement. You can find it under the heading: “Redirect Add to Cart in Quick View Modal in OceanWP Theme to External URLs”
Hi Leroy, You can add the code to your child theme’s functions.php file or use a plugin like Code Snippets, which makes it easy to apply custom code. If you have any questions or face any issues while doing this, feel free to reach us for assistance.
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?
Hi Shane, I tried to replicate the issue on my end, but the code doesn’t add the item to the WooCommerce cart. You can refer to this video link: https://go.screenpal.com/watch/cZXIfRnVhlZ. Try disabling all other plugins except WooCommerce and temporarily switching to a default theme to see if any of them might be affecting this behavior. If the issue’s still popping up, could you let us know about any other customizations you’ve made for variations? That’ll help us sort it out more easily!
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.
Glad that it works well for you! I have updated the post to add optional button text and please check the revised code. Also, I have checked the code with the plugin that you have mentioned but the custom field values added in the plugin’s interface are not getting saved in the database. For detailed assistance in making the code snippet compatible with the WPC Variation Bulk Editor, I recommend reaching out to the plugin support team.
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.
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 🙂
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.
Hi Paul, We have found a compatible plugin that works with the code, allowing bulk editing of custom fields, specifically for the _external_url and _button_text custom field values. We have updated our post and you can find the detailed steps on how to implement this functionality with a plugin below the topic titled as “Integrate External Links with Bulk Editing Plugins”.
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.
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 »
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!
Hi Anita,
I’m really glad to hear the solution worked on the main product page. To help resolve the issue with the Quick View popup modal, could you please provide some additional details, like whether you are using any plugin or a theme feature for the Quick View modal? This will help me replicate your setup and suggest the right fix.
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
Hi Anita,
We’ve worked on a solution based on your requirement. You can find it under the heading: “Redirect Add to Cart in Quick View Modal in OceanWP Theme to External URLs”
Where do I have to upload the code? Thank you
Hi Leroy,
You can add the code to your child theme’s functions.php file or use a plugin like Code Snippets, which makes it easy to apply custom code. If you have any questions or face any issues while doing this, feel free to reach us for assistance.
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?
Hi Shane,
I tried to replicate the issue on my end, but the code doesn’t add the item to the WooCommerce cart. You can refer to this video link: https://go.screenpal.com/watch/cZXIfRnVhlZ.
Try disabling all other plugins except WooCommerce and temporarily switching to a default theme to see if any of them might be affecting this behavior. If the issue’s still popping up, could you let us know about any other customizations you’ve made for variations? That’ll help us sort it out more easily!
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.
Hi paul,
Glad that it works well for you! I have updated the post to add optional button text and please check the revised code. Also, I have checked the code with the plugin that you have mentioned but the custom field values added in the plugin’s interface are not getting saved in the database. For detailed assistance in making the code snippet compatible with the WPC Variation Bulk Editor, I recommend reaching out to the plugin support team.
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.
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
Hi Paul,
Thank you for your reply! Glad to know that you found a plugin that works with the _external_url and _button_text fields from the snippet.
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.
Hi Paul,
We have found a compatible plugin that works with the code, allowing bulk editing of custom fields, specifically for the _external_url and _button_text custom field values. We have updated our post and you can find the detailed steps on how to implement this functionality with a plugin below the topic titled as “Integrate External Links with Bulk Editing Plugins”.
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/
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 »