Super Forms
  • Drag & Drop Form Builder for WordPress
  • Quick start
    • Installation
    • Registration
    • Starting your 15 day trial
    • Purchasing a license
    • Activating a license
    • First time setup
    • Secure file uploads
    • Creating a form
    • Adding form elements
    • Editing elements
    • Publishing your form
    • FAQ
  • Account
    • Dashboard
      • Your Invoices
      • Billing details
      • Your Licenses
      • E-mail Notification
      • Password reset
      • Cancel subscription
  • Common problems
    • Common problems
      • Email delivery problems
        • Why is my form not sending emails?
        • Why are emails going into spam folder/inbox?
      • File upload problems
      • Session expired
      • reCaptcha Troubleshooting – Fix “Not Loading” & Verification Errors
  • Elements
    • Layout elements
      • Column/Grid
      • Multi-part / step
    • Form elements
      • Calculator
      • Signature
      • File upload
      • Datepicker
      • Variable field
      • Dropdown
      • Text field
      • Autosuggest
      • Keywords
      • Radio button
      • Keyword Field
      • Button
      • Audio Recording (microphone)
    • HTML elements
      • Heading
      • HTML (raw)
      • Image
      • TinyMCE
      • Divider
      • Spacer
      • PDF page break
      • Google map element WordPress form
  • Features
    • Basic
      • Confirmations emails
      • Save Form Progression (continue later)
      • Build In Translation System
      • Populate form
      • Popups
      • Import & Export
      • Hide form after submitting
      • Hide or lock out user from your forms
      • Validation
    • Advanced
      • WordPress form with Google sheets dropdown
      • Custom registration form for WordPress
      • Custom login form for WordPress
      • Custom lost password form for WordPress
      • Update current logged in user
      • Secrets
      • Prevent duplicate entries
      • Lock & hide form
      • Password protect
      • Conditional Logic
      • Tags system
      • Address lookup/auto complete
      • Analytics Tracking
      • Conversion Tracking
      • Distance & Duration Calculation
      • If statements
      • Foreach loops
      • E-mail Reminders
      • Variable Fields
      • Form templates - Include elements into other forms - WordPress
      • Transferring data from one form to another
    • Integrations
      • PDF Generator
      • Listings
      • WooCommerce Checkout
        • Fixed price checkout
        • Dynamic price checkout
        • Variable product checkout (variations)
        • Replacing the "Add to cart" on a product page with a form
        • Hiding product from shop and order via custom form
      • PayPal
      • MailChimp
      • Mailster
      • Zapier
      • Stripe (BETA)
      • WooCommerce Instant Order (in progress)
  • Tutorials
    • WordPress Form to Google Sheet Integration
    • GDPR Consent / Terms agreement
    • How to update the plugin
    • Sending emails to specific department for WordPress contact forms
  • Example Forms for WordPress
    • Booking 24 hours ahead of time
  • Developers
    • Code Examples
      • Lookup City by Zipcode for your WordPress form
      • Audio Recording Field
      • Custom API Phone Number Validation for Your WordPress Form
      • Updating WordPress user meta data after login
      • Automatically redirecting to next step after displaying text or a progress bar
      • Dropdown with groups (categories)
      • Prevent form submission based on entered field values
      • Track form submissions with GTM (Google Tag Manager)
      • Tracking Multi-part steps with Google Analytics
      • Tracking Multi-part steps with GTM data layer (dataLayer.push)
      • Track form submissions with third party
      • Compare input field value with database value
      • Insert form data into a custom database table
      • Delete database row after contact entry is deleted in WordPress
      • Limited date availability (slots) for your WordPress booking form
      • Send submitted form data to another site
      • Exclude empty fields from emails
      • Execute custom JS when a column becomes conditionally visible
      • Toolset Plugin: Update comma separated string to Array for meta data saved via Front-end Posting
      • Toolset Plugin: Update file ID to file URL for meta data saved via Front-end Posting
      • Delete uploaded files after email has been send
      • Increase Cookie lifetime for client data such as [Form Progression]
      • Altering cookie secure and httponly parameters
      • Define fake cronjob to clear old client data if cronjob is disabled on your server
      • Define page language attribute based on page ID or URL
      • Define custom headers when doing a POST request
      • Change checkbox/radio layout to vertical on mobile devices
      • Show remaining available form submission allowed
      • Global fields / elements
      • Trim values of fields
      • Re-sending E-mails after editing entries via Listings for WordPress
      • Combine multiple field values into one column on Contact Entries page
      • Altering the attachments for E-mails via PHP code for WordPress
      • Generate dynamic columns with dates based on user selected date from Datepicker element
      • Hide `eye` icon from Listings row based on user role
      • Variable product checkout based on variation SKU
    • Data storage
    • BETA version
  • Changelog
  • Support
Powered by GitBook
On this page
  1. Developers
  2. Code Examples

Variable product checkout based on variation SKU

This example code allows you to use variable fields inside your form to generate the SKU dynamically based on user selected options. Allowing you to add the product variation to the cart base on SKU.

Below PHP code is an example where we would ask a user to select their base product, a color, and the size of the product. We then use a variable field to create the desired SKU e.g. {product}_{color}_{size} which the script then translates to the actual variation ID.

Simply define the Enter the product(s) ID that needs to be added to the car h in your WooCommerce Checkout settings, to {sku}|{quantity} where your form would contain a field named sku which will hold the generated SKU.

Of course an actual SKU should exists in order for the product to be added to the cart.

You can add below to your child theme functions.php

// Add WooCommerce variable product to cart based on variation SKU, e.g. if you have SKU: `product1_red_xxl` 
// the below script will lookup the variation ID based on this SKU, and update the passed variation_id to the WC add_to_cart() function
// In the below code we added a check to based on variable field value 
// Make sure to set the WooCommerce setting `Enter the product(s) ID that needs to be added to the cart` to something like:
// {sku}|{quantity}
// where `sku` would be your variable field that would set the correct SKU based on user selected options in your form e.g: `{product}_{color}_{size}`
// below filter is only available from the latest github commit (16 May, 2025)
add_filter('super_before_adding_wc_products_to_cart_filter', 'superforms_resolve_variation_from_id_sku', 10, 2);
function superforms_resolve_variation_from_id_sku($products, $context){
    foreach($products as &$product){
        if(isset($product['id']) && is_string($product['id'])){
            $sku = trim($product['id']);
            // (optional) Check if SKU has exactly 3 parts (e.g., product1_red_xxl)
            // $parts = explode('_', $sku);
            // if(count($parts)!==3) continue; // Not a custom SKU
            // Try to resolve variation by SKU
            $variation_id = wc_get_product_id_by_sku($sku);
            if(!$variation_id){
                wc_add_notice("Invalid SKU: $sku", 'error');
                continue;
            }
            $variation = wc_get_product($variation_id);
            if(!$variation || !$variation->is_type('variation')){
                wc_add_notice("SKU does not match a product variation: $sku", 'error');
                continue;
            }
            $parent_id   = $variation->get_parent_id();
            $attributes  = $variation->get_attributes();
            // Override fields
            $product['id'] = $parent_id;
            $product['variation_id'] = $variation_id;
            $product['variation_attributes'] = $attributes;
        }
    }
    return $products;
}

Example form code:

[
    {
        "tag": "dropdown",
        "group": "form_elements",
        "data": {
            "name": "product",
            "email": "Option:",
            "dropdown_items": [
                {
                    "checked": false,
                    "label": "A",
                    "value": "a"
                },
                {
                    "checked": false,
                    "label": "B",
                    "value": "b"
                },
                {
                    "checked": false,
                    "label": "C",
                    "value": "c"
                }
            ],
            "placeholder": "- select a option -",
            "icon": "caret-square-down;far"
        }
    },
    {
        "tag": "quantity",
        "group": "form_elements",
        "data": {
            "name": "quantity",
            "email": "Quantity:",
            "minnumber": "1"
        }
    },
    {
        "tag": "dropdown",
        "group": "form_elements",
        "data": {
            "name": "frequency",
            "email": "Option:",
            "dropdown_items": [
                {
                    "checked": false,
                    "label": "Monthly",
                    "value": "monthly"
                },
                {
                    "checked": false,
                    "label": "Yearly",
                    "value": "yearly"
                }
            ],
            "placeholder": "- select a option -",
            "icon": "caret-square-down;far"
        }
    },
    {
        "tag": "dropdown",
        "group": "form_elements",
        "data": {
            "name": "payment",
            "email": "Option:",
            "dropdown_items": [
                {
                    "checked": false,
                    "label": "Monthly",
                    "value": "monthly"
                },
                {
                    "checked": false,
                    "label": "Yearly",
                    "value": "yearly"
                }
            ],
            "placeholder": "- select a option -",
            "icon": "caret-square-down;far"
        }
    },
    {
        "tag": "hidden",
        "group": "form_elements",
        "data": {
            "name": "sku",
            "email": "Variable:",
            "conditional_variable_action": "enabled",
            "conditional_variable_items": [
                {
                    "field": "{product}",
                    "logic": "not_equal",
                    "value": "",
                    "and_method": "",
                    "field_and": "",
                    "logic_and": "",
                    "value_and": "",
                    "new_value": "{product}_{frequency}_{payment}"
                }
            ]
        }
    },
    {
        "tag": "html",
        "group": "html_elements",
        "data": {
            "name": "html",
            "email": "HTML:",
            "html": "product: {product}\nfrequency: {frequency}\npayment: {payment}\n\n\nSKU value: {sku}",
            "exclude": "2",
            "exclude_entry": "true"
        }
    }
]
PreviousHide `eye` icon from Listings row based on user roleNextData storage

Last updated 21 days ago