WooCommerce: Add input field to every item in cart

前端 未结 3 529
灰色年华
灰色年华 2020-11-29 02:17

I\'ve been trying to add a single text input field to every item in the cart and submit that user input to product\'s meta info. It\'s been 2 days and I haven\'t succeeded y

3条回答
  •  长情又很酷
    2020-11-29 02:35

    There is a wordpress plugin called WC Fields Factory for the exact purpose.

    You can also achieve this by using the following woocommerce hooks woocommerce_before_add_to_cart_button, woocommerce_add_to_cart, woocommerce_cart_item_name,and 'woocommerce_add_order_item_meta'

    like for adding text field to product page

    function add_name_on_tshirt_field() {
      echo '
    '; } add_action( 'woocommerce_before_add_to_cart_button', 'add_name_on_tshirt_field' );

    For displaying custom field on cart item table use the below

    function render_meta_on_cart_item( $title = null, $cart_item = null, $cart_item_key = null ) {
        if( $cart_item_key && is_cart() ) {
            echo $title. '
    Name On T-Shirt :

    '. WC()->session->get( $cart_item_key.'_name_on_tshirt') .'

    '; }else { echo $title; } } add_filter( 'woocommerce_cart_item_name', 'render_meta_on_cart_item', 1, 3 );

    to make your custom meta data on you order details, do some thing like this

    function tshirt_order_meta_handler( $item_id, $values, $cart_item_key ) {
        wc_add_order_item_meta( $item_id, "name_on_tshirt", WC()->session->get( $cart_item_key.'_name_on_tshirt') );    
    }
    add_action( 'woocommerce_add_order_item_meta', 'tshirt_order_meta_handler', 1, 3 );
    

    for detailed implementation, i have an article about how to do this without using any plugins. http://sarkware.com/how-to-pass-custom-data-to-cart-line-item-in-woocommerce-without-using-plugins/

提交回复
热议问题