• Join the Best Wordpress and Elementor Support forum

    Provide or get advice on everything Elementor and Wordpress, ask questions, gain confirmation or just become apart of a friendly, like minded community who love Wordpress and Elementor


    Join us!

How to add a cutom field to Woocommerce varitations and include into purchase emails

Community

Community

Administrator
Staff member
This is for a customer who wanted to add a link to variations, of which the link is then displayed in a customers email once purchased.

The idea being that upon puchasing of the product, the customer can then goto a link to access the data they've purchased or a certificate. This code can be adapted to suit different types of custom fields and data.


PHP:
/**
 * Add custom link field to variations
 */
add_action('woocommerce_product_after_variable_attributes', 'add_variation_custom_link_field', 10, 3);
function add_variation_custom_link_field($loop, $variation_data, $variation) {
    woocommerce_wp_text_input([
        'id' => 'custom_link_' . $loop,
        'name' => 'custom_link[' . $loop . ']',
        'value' => get_post_meta($variation->ID, 'custom_link', true),
        'label' => __('Custom Link', 'your-text-domain'),
        'desc_tip' => true,
        'description' => __('Add a custom link to be included in order emails', 'your-text-domain'),
        'wrapper_class' => 'form-row',
        'placeholder' => 'https://example.com/file.pdf'
    ]);
}

/**
 * Save custom link field value
 */
add_action('woocommerce_save_product_variation', 'save_variation_custom_link_field', 10, 2);
function save_variation_custom_link_field($variation_id, $loop) {
    if (isset($_POST['custom_link'][$loop])) {
        update_post_meta(
            $variation_id,
            'custom_link',
            esc_url_raw($_POST['custom_link'][$loop])
        );
    }
}

/**
 * Display custom link in order emails
 */
add_action('woocommerce_order_item_meta_end', 'add_custom_link_to_emails', 10, 4);
function add_custom_link_to_emails($item_id, $item, $order, $plain_text) {
    // Only for emails and variations
    if (!is_admin() && $item->get_type() === 'line_item' && $item->get_variation_id()) {
        $custom_link = get_post_meta($item->get_variation_id(), 'custom_link', true);
        
        if ($custom_link) {
            echo '<div class="custom-link"><strong>' . esc_html__('Download Link:', 'your-text-domain') . '</strong> ';
            echo '<a href="' . esc_url($custom_link) . '" target="_blank">' . esc_html__('Click here to download', 'your-text-domain') . '</a></div>';
        }
    }
}
 

Latest Resources

Other Elementor Resources

elementor official

Still stuck? Ask the forum

Post your question with a screenshot and a link if you can, and a member will usually reply within a day. Free to join, no sales pitch.

Create a free account
Top