Search code examples
phpwordpresswoocommercemetadatahook-woocommerce

Get meta data via "woocommerce_order_get_formatted_billing_address" filter hook


Im trying to apply a custom post meta field billing_company_id to orders formatterd billing address, and place it below billing company.

Via the following code I can apply a string but how to get the custom post meta from an order?

add_action( 'woocommerce_order_get_formatted_billing_address', 'company_billing_id', 20, 1 );
function company_billing_id($address){
    $address .= 'Custom field string'; 
    return $address;
}

Solution

  • The woocommerce_order_get_formatted_billing_address filter hook contains not 1 but 3 parameters.

    Via the 3rd you have access to the $order object, so you could use something like:

    /**
     * Filter orders formatterd billing address.
     *
     * @since 3.8.0
     * @param string   $address     Formatted billing address string.
     * @param array    $raw_address Raw billing address.
     * @param WC_Order $order       Order data. @since 3.9.0
     */
    function filter_woocommerce_order_get_formatted_billing_address( $address, $raw_address, $order ) {
        // Get meta
        $value = $order->get_meta( 'billing_company_id' );
    
        // NOT empty
        if ( ! empty ( $value ) ) {
            // Append
            $address .= $value;
        }
    
        return $address;
    }
    add_filter( 'woocommerce_order_get_formatted_billing_address', 'filter_woocommerce_order_get_formatted_billing_address', 10, 3 );