How to add a textarea field value to a custom table in WooCommerce checkout?

80 Views Asked by At

i am trying to write my custom textarea inputs into a custom wordpress table when an order is created. Unfortunately, the custom textarea inputs are not saved in my custom table. Only a ";" is stored in the table column "cardcontent" of my custom table. I tried to access my custom textarea inputs with $_POST.

Process:

  1. I have custom textarea fields that should be processed into the cart object (see the following code)
<div id="cardcontent" class="cardcontent old">
   <div id="cardcontentwrapper">
      <textarea id='heading' name='heading' placeholder='Please enter a title' class='heading' rows="1" cols="50"></textarea><span id="heading-length-left"></span>
      <textarea id='bodytext' name='bodytext' placeholder='Please enter a message' class='bodytext' rows="1" cols="50"></textarea>
   </div>
</div>
  1. My fields are added to the order in custom.js file with the following hook:
// hook triggered when pressing the Add to cart button - copy heading and body inputs to cart form
wp.hooks.addAction( 'PC.fe.add_to_cart.before', 'your_namespace', function( view ) { 
    // Get the add to cart form, which is stored in the view
    var $cart_form = view.$cart;
    jQuery( '.mkl_pc_layers .custom-html.active textarea.heading' ).clone().appendTo( $cart_form );
    jQuery( '.mkl_pc_layers .custom-html.active textarea.bodytext' ).clone().appendTo( $cart_form );
});
  1. I try to access my custom field values with the following code in functions.php via $_POST:
//triggers before checkout form is submited but order will be created.
add_action( 'woocommerce_checkout_update_order_meta', 'cpm_woocommerce_checkout_update', 10, 2 );

function cpm_woocommerce_checkout_update($order_id, $data) {
    
    //trying to get my textarea input values with $_POST
    $cardHeading = $_POST['heading'];
    $cardBody = $_POST['bodytext']; 
    
    $order = wc_get_order( $order_id );
        
    global $wpdb;
        
    $card = $cardHeading . ";" . $cardBody;
    $timestamp = time();
    $id = 1;
        
    $table_name =  $wpdb->prefix."cards";
    $data = array( 
            'userid' => $id,
            'orderid' => $order_id,
            'cardcontent' => $card,
            'timestamp' => $timestamp,
    );
    $wpdb->insert( $table_name, $data );
}

Desired behavior: I want my custom textarea inputs to be processed via $_POST into the order and store the values as a string in my custom table column cardcontent.

Problem: Only ";" is stored in the db, because the values are not getting fetched.

Question: How to access the custom fields with $_POST and attach them to the cart? Or do i have to attach them to the order object?

0

There are 0 best solutions below