Vinith Almeida
Vinith Almeida

Reputation: 1471

Edit the content of "address_1" field in the woocommerce checkout form before saving

I have modified the placeholder of the address_1 field on the checkout page to prompt users to enter the landmark.

function custom_override_default_address_fields( $address_fields ) {
    $address_fields['address_1']['placeholder'] = "Landmark";
    return $address_fields;
}
add_filter( 'woocommerce_default_address_fields' , 'custom_override_default_address_fields' );

I would like the value when saved in the database to be prepended by the text Landmark: and then the value entered by the user.

What hook do I use to grab the value and how do I modify it before it gets saved in the database?

Upvotes: 0

Views: 31

Answers (1)

Richard
Richard

Reputation: 489

To prepend "Landmark:" to the value of "address_1" you will need to use another filter hook, like woocommerce_checkout_create_order. This hook gives you more control over the order data when it's being created, and is used to modify the order data before it gets saved to the database (reference).

Please note that, woocommerce_checkout_create_order is not triggered, if you are using the WooCommerce block checkout (reference).

Also, since WooCommerce sepeates billing and shipping fields, you will need to target each one specifically.

The below code should prepend "Landmark: " to "address_1" field values before they are saved to both the WooCommerce backend and the database, if the field is not empty:

// Add a filter to modify the placeholder text for the address_1 field
add_filter( 'woocommerce_default_address_fields', 'custom_override_default_address_fields' );
function custom_override_default_address_fields( $address_fields ) {
    // Set the placeholder for address_1 field to "Landmark"
    $address_fields['address_1']['placeholder'] = "Landmark";
    return $address_fields;
}

// Add action to modify order data
add_action( 'woocommerce_checkout_create_order', 'prepend_landmark_to_address_1', 20, 2 );
function prepend_landmark_to_address_1( $order, $data ) {
    // Check if billing address_1 field is set and not empty
    if ( isset( $data['billing']['address_1'] ) && !empty( $data['billing']['address_1'] ) ) {
        // Prepend "Landmark: " to the billing address_1 value
        $order->set_billing_address_1( 'Landmark: ' . $data['billing']['address_1'] );
    }
    // Check if shipping address_1 field is set and not empty
    if ( isset( $data['shipping']['address_1'] ) && !empty( $data['shipping']['address_1'] ) ) {
        // Prepend "Landmark: " to the shipping address_1 value
        $order->set_shipping_address_1( 'Landmark: ' . $data['shipping']['address_1'] );
    }
}

Upvotes: 0

Related Questions