Add Custom attributes from a variable product to cart in WooCommerce

10,270

Solution 1

Updated

This "Business Bloomer" guide is a little outdated… You need 2 things:

1). The correct URL

You don't need to addto cart the product and the variation Id with all related attributes. You just need to add to cart the variation ID + your custom attributes like this: localhost/wordpress/cart/?add-to-cart=1641&quantity=1&pa_liability=2_million&pa_hours=500_hours

2). Registering (and display) your custom attributes:

// Store the custom data to cart object
add_filter( 'woocommerce_add_cart_item_data', 'save_custom_product_data', 10, 2 );
function save_custom_product_data( $cart_item_data, $product_id ) {
    $bool = false;
    $data = array();
    if( isset( $_REQUEST['pa_liability'] ) ) {
        $cart_item_data['custom_data']['pa_liability'] = $_REQUEST['pa_liability'];
        $data['pa_liability'] = $_REQUEST['pa_liability'];
        $bool = true;
    }
    if( isset( $_REQUEST['pa_hours'] ) ) {
        $cart_item_data['custom_data']['pa_hours'] = $_REQUEST['pa_hours'];
        $data['pa_hours'] = $_REQUEST['pa_hours'];
        $bool = true;
    }
    if( $bool ) {
        // below statement make sure every add to cart action as unique line item
        $cart_item_data['custom_data']['unique_key'] = md5( microtime().rand() );
        WC()->session->set( 'custom_variations', $data );
    }
    return $cart_item_data;
}

// Displaying the custom attributes in cart and checkout items
add_filter( 'woocommerce_get_item_data', 'customizing_cart_item_data', 10, 2 );
function customizing_cart_item_data( $cart_data, $cart_item ) {
    $custom_items = array();
    if( ! empty( $cart_data ) ) $custom_items = $cart_data;

    // Get the data (custom attributes) and set them
    if( ! empty( $cart_item['custom_data']['pa_liability'] ) )
        $custom_items[] = array(
            'name'      => 'pa_liability',
            'value'     => $cart_item['custom_data']['pa_liability'],
        );
    if( ! empty( $cart_item['custom_data']['pa_hours'] ) )
        $custom_items[] = array(
            'name'      => 'pa_hours',
            'value'     => $cart_item['custom_data']['pa_hours'],
        );
    return $custom_items;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works

You will need to add this data to the order items too

Solution 2

First uncheck the ajax add to cart option from admin panel Then you need to make variation with your attributes then find out product id, quantity, attribute slug and attribute name(used to show in cart) and variation id and then make your cart url like given below.

The add to cart link with attribute is : https://www.your-domain.com/?add-to-cart=(product id)&quantity=(numeric quantity)&attribute_pa_(attribute slug)=(attribute name)&variation_id=(variation id)

For more details you can visit http://www.codemystery.com/wordpress-woocommerce-add-cart-link-variations/

Share:
10,270
Sunny Ramrakhiani
Author by

Sunny Ramrakhiani

Updated on June 04, 2022

Comments

  • Sunny Ramrakhiani
    Sunny Ramrakhiani almost 2 years

    I am trying to redirect my custom shop page to cart page after user select custom attributes (liability and hours) and then clicks the purchase button.

    I have written custom JS code which retrieves the variation_id and attributes value and append it to the URL so that it automatically gets added to cart and get's redirected to cart page.

    href="yourdomain.com/?add-to-cart=47&variation_id=88&quantity=3&attribute_pa_colour=blue&attribute_pa_size=m"
    

    This is the URL format which I have found in a blog: (https://businessbloomer.com/woocommerce-custom-add-cart-urls-ultimate-guide/) and I made my link in this format.

    My link is:

    localhost/wordpress/cart/?add-to-cart=1185&variation_id=1641&quantity=1&attribute_pa_liability=2_million&attribute_pa_hours=500_hours
    

    Where liability and hours is my custom attribute which has values as 1 million, 2 million and 500 hours, 750 hours respectively.

    But when it get's redirected to cart page woocommerce give me an error and shows it's alert box which shows the error message as "liability and hours are required fields".

    I think woocommerce is unable to get the attribute values through my URL.

    Can anyone explain why is this happening and what is the error if there is any?

    • madalinivascu
      madalinivascu over 6 years
      how do you get those properties on the checkout page?
    • Sunny Ramrakhiani
      Sunny Ramrakhiani over 6 years
      I retrieve the values of attribute_pa_liability and attribute_pa_hours from $_GET in a function membership_forms_handler and it checks if all the attribute drop-down are selected and retrieves the value and creates the link to which user is redirected. Below is the code which is used, $redirect_url = home_url()."/cart/?add-to-cart=".$_GET["membership_product"]‌​."&variation_id=".$_‌​GET['variation_id'].‌​"&quantity=".$_GET["‌​quantity"]."&attribu‌​te_pa_liability=".$_‌​GET['attribute_pa_li‌​ability']."&attribut‌​e_pa_hours=".$_GET['‌​attribute_pa_hours']‌​; wp_redirect($redirect_url);
    • madalinivascu
      madalinivascu over 6 years
      and when the user is redirected how do you fetch the params on that page?i mean on localhost/wordpress/cart/?add-to-cart=1185&variation_id=1641‌​&quantity=1&attribut‌​e_pa_liability=2_mil‌​lion&attribute_pa_ho‌​urs=500_hours
    • Sunny Ramrakhiani
      Sunny Ramrakhiani over 6 years
      I assume that should be done by woocommerce itself as it was in the blog from which i got the URL format, businessbloomer.com/…
    • waka
      waka over 6 years
      Please edit your code into the question, don't add it as comments.
    • Sunny Ramrakhiani
      Sunny Ramrakhiani over 6 years
      @LoicTheAztec Thanks for your help, Actually I was displaying drop-down of attributes using WordPress function wc_dropdown_variation_attribute_options($args) which takes an object as argument in which we can mention the name and class of our HTML select which should be used to access its values and in javascript functions, my problem was that my name of HTML select was different and name in the link was different hence woocommerce was throwing error as it was expecting values with different name. Your problem is also correct as you are using same name in the link as well as in other variables
    • LoicTheAztec
      LoicTheAztec over 6 years
      @SunnyRamrakhiani You should add the necessary code related in your question as it's not possible to guess that… This can allow me to complete my answer and make it useful for others.
  • seedme
    seedme almost 3 years
    this appears to me as a valid answer that WP+WooCommerce natively supports.