WooCommerce: How to display fields from the “Product Add-ons” extension?

后端 未结 2 2155
无人共我
无人共我 2021-02-14 12:17

I\'m using the [Product Add-ons][1] extension for WooCommerce, which allows custom fields for products. This automatically displays on the single product template.

By s

2条回答
  •  遇见更好的自我
    2021-02-14 13:09

    I've found a solution that works, using jQuery to add the form field values to the AJAX request. This requires overriding add-to-cart.js with your own version, so future updates to that file may need to be merged.

    In functions.php

    // display add-on fields in woocommerce_after_shop_loop_item_title
    add_action( 'woocommerce_after_shop_loop_item_title', array($GLOBALS['Product_Addon_Display'], 'display'), 10);
    
    // Our custom cart JS to allow for product add-on fields on product archive
    add_action( 'wp_enqueue_scripts', 'load_woo_scripts', 9 );
    function load_woo_scripts() { 
        wp_enqueue_script( 'wc-add-to-cart', get_template_directory_uri() . '/js/add-to-cart.js', array( 'jquery' ), WC_VERSION, true );
    }
    

    Duplicate /assets/add-to-cart.js from the woocommerce plugin folder, and add to the folder referenced in load_woo_scripts. Then add the following after the var date = { statement (line 21).

    // =========================================================================
    // ADD PRODUCT ADD-ON FIELDS TO SUBMISSION (to allow from product archive)
    // Store name and value of fields in object.
    var addonfields = {}; 
    $(this).parent().find(".after-shop-loop-item-title :input").each(function() { 
        addonfields[this.name] = $(this).val(); 
    }); 
    
    // Merge new fields and existing data
    data = $.extend(data, addonfields);
    
    // Testing: final value of data
    console.log( data );
    // =========================================================================
    

    This adds the names and values of all input fields within the .after-shop-loop-item-title div. I've added this div/class to my theme's woocommerce/content-product.php template:

    
    

    Note that in my case, I am only using a textarea and a text input. Neither of which changes the price. More advanced usage of the extension may require more work.

    I really hope that WooCommerce makes this easier in the future...

提交回复
热议问题