WP SITES

3086 Coded Tutorials & 289 Plugins

Add External URL to Product Variations for WooCommerce

This code adds a custom field to each variation enabling the add to cart button to link to any URL on variation selection and also change the button text to Buy Now.

// 1. Add External URL field to each variation in admin
add_action('woocommerce_product_after_variable_attributes', 'add_external_url_field_to_variations', 10, 3);
function add_external_url_field_to_variations($loop, $variation_data, $variation) {
    woocommerce_wp_text_input([
        'id' => "_external_url[$loop]",
        'label' => 'External URL',
        'desc_tip' => true,
        'description' => 'Enter the external URL for this variation',
        'value' => get_post_meta($variation->ID, '_external_url', true),
    ]);
}

// 2. Save the External URL field value
add_action('woocommerce_save_product_variation', 'save_external_url_variation_field', 10, 2);
function save_external_url_variation_field($variation_id, $i) {
    if (isset($_POST['_external_url'][$i])) {
        update_post_meta($variation_id, '_external_url', esc_url_raw($_POST['_external_url'][$i]));
    }
}

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

// 4. Front-end script to redirect "Add to Cart" to external URL
add_action('wp_footer', 'variation_redirect_script');
function variation_redirect_script() {
    if (!is_product()) return;
    ?>
    <script>
    jQuery(function($) {
        $('form.variations_form').on('show_variation', function(event, variation) {
            if (variation.external_url) {
                const $form = $(this);
                const $button = $form.find('.single_add_to_cart_button');
                $button
                    .text('Buy Now')
                    .removeClass('disabled')
                    .off('click')
                    .on('click', function(e) {
                        e.preventDefault();
                        window.open(variation.external_url, '_blank');
                    });
            } else {
                const $button = $(this).find('.single_add_to_cart_button');
                $button
                    .text('<?php echo esc_js(__('Add to cart', 'woocommerce')); ?>')
                    .off('click');
            }
        });
    });
    </script>
    <?php
}

Add the code at the end of your child themes functions.php file or custom code snippets plugin.

Leave a Reply

New Plugins