Fix or Disable Checkout Fields for Additional Orders of WooCommerce

Read, learn, and grow with our expertly curated blog posts tailored just for you.

Fix or Disable Checkout Fields for Additional Orders of WooCommerce
🕒
2 mins read

If you like to fix all the fields on the checkout form. Let’s suppose customer placing the additional order which may confuse you if he has filled different details then you can fix/disable all the fields as shown below:

/**
 * Disable all the Fields to make them fixed as the customer used for the previous order
 *
 * @param  array $fields
 * @return array
*/
function fix_customer_details( $fields ) {
  global $wpdb;

  // Get current user ID
  $user_id = get_current_user_id();

  $post_types      = wc_get_order_types();
  $comma_separated = implode( "','", $post_types );
  $comma_separated = "'" . $comma_separated . "'";
  $sql_query = "
    SELECT post_id FROM $wpdb->posts
    INNER JOIN $wpdb->postmeta ON post_id = ID
    WHERE post_type IN (" . $comma_separated . ")
      AND post_status = 'wc-processing'
      AND meta_key = '_customer_user'
      AND meta_value = " . $user_id . "
    ORDER BY post_id";
  $items = $wpdb->get_results( $sql_query );
  if ( ! empty( $items ) ) { // only for additional orders
    if ( isset( $fields['billing'] ) ) {
      foreach ( $fields['billing'] as $key => $value ) {
        if ( ! isset( $fields['billing'][$key]['type'] ) ) {
          $fields['billing'][$key]['custom_attributes'] = array( 'readonly' => true );
        }
      }
    }
    if ( isset( $fields['shipping'] ) ) {
      foreach ( $fields['shipping'] as $key => $value ) {
        if ( ! isset( $fields['shipping'][$key]['type'] ) ) {
          $fields['shipping'][$key]['custom_attributes'] = array( 'readonly' => true );
        }
      }
    }
  }

  return $fields;
}

add_filter( 'woocommerce_checkout_fields', 'fix_customer_details', 10, 1 );

Note: Make sure that you add the readonly attribute to disable the fields if you use disabled attribute in it then it may start throwing error that the fields are required as Disabled <input> elements in a form will not be submitted!

If you like to fix/disabled some fields only so you can do that as shown here.