| |

WooCommerce Function of the Week: get_ip_address

The get_ip_address function is useful for tracking visitors who aren't logged in as they move through key pages in your store.

Whether it's for troubleshooting payments, creating user history logs or enabling custom geolocation, there is a WooCommerce function that lets you forget about all the $_SERVER global keys and gets you an immediate result: the current user's IP address.

You can store an IP address in a custom field or use it to trigger another custom function. Bear in mind, IP addresses are personal identification data and therefore regulated by the GDPR: “That means that some form of justification like user consent would always be needed as soon as the IP address is processed.”

So, let's take a look at the function code, its usage, and a case study.

Function code

The function get_ip_address can be found under \woocommerce\includes\class-wc-geolocation.php:

/**
 * Get current user IP Address.
 *
 * @return string
 */
public static function get_ip_address() {
	if ( isset( $_SERVER['HTTP_X_REAL_IP'] ) ) {
		return sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_REAL_IP'] ) );
	} elseif ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
		// Proxy servers can send through this header like this: X-Forwarded-For: client1, proxy1, proxy2
		// Make sure we always only send through the first IP in the list which should always be the client IP.
		return (string) rest_is_ip_address( trim( current( preg_split( '/,/', sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) ) ) ) );
	} elseif ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
		return sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) );
	}
	return '';
}

First of all, notice it's a function inside a class, WC_Geolocation, so it can't be called in the usual way by simply typing its name β€” we also need to reference the class.

Other than that, the function checks for several $_SERVER key/values, and based on whether they are set or not it returns the IP address as a string e.g. “123.456.789.0.”

As a developer, I have no intention of understanding the difference between $_SERVER['HTTP_X_REAL_IP'], $_SERVER['HTTP_X_FORWARDED_FOR'], and $_SERVER['REMOTE_ADDR']. All I care about is the final result, so that I can speed up my custom coding operations.

Function usage

As I mentioned earlier, the function can be called with the following statement:

WC_Geolocation::get_ip_address(); // CORRECT

Because it's a function inside a class, the class must be specified. Calling this in your custom snippet or plugin would throw an error:

get_ip_address(); // WRONG

Now that we know how to call it, let's see what WooCommerce does with it.

In \woocommerce\includes\class-wc-checkout.php we find the following statement:

public function create_order( $data ) {
   /* .... */
   $order->set_customer_ip_address( WC_Geolocation::get_ip_address() );

That's right β€” upon order creation during checkout, the customer IP address is saved to the order as custom metadata.

Another call can be found under \woocommerce\includes\wc-core-functions.php:

function wc_create_order( $args = array() ) {
   /* ... */
   $order->set_customer_ip_address( WC_Geolocation::get_ip_address() );

This time, it's for orders created programmatically β€” i.e., not through the checkout.

It's now evident that the only reason that function is there is to display this:

So, let's see if we can use the function for other purposes.

Function case study

As we said earlier, and if you're allowed under your country's regulations, you may use the IP address for different scenarios.

The first that comes to mind is coding some custom tracking for a customer who isn't logged in to a user account. You could use that tracking method to troubleshoot cart abandonment or understand your customer's path out of the sales cycle.

You could call the function on the “add to cart” hook:

do_action( 'woocommerce_add_to_cart', $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data );

Or you could call it in the cart page “proceed to checkout” hook, which is equivalent to calling any checkout hook:

do_action( 'woocommerce_before_checkout_form' );

Or you could call it on the thank you page hook:

do_action( 'woocommerce_thankyou' );

In this way, you can follow a visitor who is not logged in along their path to or away from a conversion.

In a previous episode, we spoke about the wc_get_logger function. It's useful for creating custom logs in the WooCommerce admin, so let's make the most of it and create a custom log for each unique IP address that hits our website and visits key WooCommerce pages:

/**
* @snippet       IP customer conversion log | WooCommerce
* @how-to        Get CustomizeWoo.com FREE
* @author        Rodolfo Melogli
* @testedwith    WooCommerce 6
* @donate $9     https://businessbloomer.com/bloomer-armada/
*/

// USER ADDS TO CART

add_action( 'woocommerce_add_to_cart', 'bbloomer_log_ip_added_to_cart', 9999, 6 );

function bbloomer_log_ip_added_to_cart( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {
   $logger = wc_get_logger();
   $logger->info( WC_Geolocation::get_ip_address() . ' added to cart product ID: ' . $product_id, array( 'source' => 'ip-path' ) );
}

// USER GOES TO CHECKOUT

add_action( 'woocommerce_before_checkout_form', 'bbloomer_log_ip_went_to_checkout' );

function bbloomer_log_ip_went_to_checkout() {
   $logger = wc_get_logger();
   $logger->info( WC_Geolocation::get_ip_address() . ' went to checkout', array( 'source' => 'ip-path' ) );
}

// USER MAKES PURCHASE

add_action( 'woocommerce_thankyou', 'bbloomer_log_ip_purchased' );

function bbloomer_log_ip_purchased() {
   $logger = wc_get_logger();
   $logger->info( WC_Geolocation::get_ip_address() . ' purchased!', array( 'source' => 'ip-path' ) );
}

This time I'll leave the testing part to you. If you want to send a screenshot of the custom log after the events trigger, feel free to do so in the comments.

The same applies if you find a bug!

Similar Posts

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.