WC_Customer_Data_Store::get_last_order()publicWC 3.0.0

Gets the customers last order.

Method of the class: WC_Customer_Data_Store{}

Hooks from the method

Return

WC_Order|false.

Usage

$WC_Customer_Data_Store = new WC_Customer_Data_Store();
$WC_Customer_Data_Store->get_last_order( $customer );
$customer(WC_Customer) (required) (passed by reference — &)
Customer object.

Changelog

Since 3.0.0 Introduced.

WC_Customer_Data_Store::get_last_order() code WC 9.4.2

public function get_last_order( &$customer ) {
	// Try to fetch the last order placed by this customer.
	$last_order_id       = Users::get_site_user_meta( $customer->get_id(), 'wc_last_order', true );
	$last_customer_order = false;

	if ( ! empty( $last_order_id ) ) {
		$last_customer_order = wc_get_order( $last_order_id );
	}

	// "Unset" the last order ID if the order is associated with another customer. Unsetting is done by making it an
	// empty string, for compatibility with the declared types of the following filter hook.
	if (
		! $last_customer_order instanceof WC_Order
		|| intval( $last_customer_order->get_customer_id() ) !== intval( $customer->get_id() )
	) {
		$last_order_id = '';
	}

	/**
	 * Filters the id of the last order from a given customer.
	 *
	 * @since 4.9.1
	 *
	 * @param string      $last_order_id The last order id as retrieved from the database.
	 * @param WC_Customer $customer      The customer whose last order id is being retrieved.
	 *
	 * @return string The actual last order id to use.
	 */
	$last_order_id = apply_filters(
		'woocommerce_customer_get_last_order',
		$last_order_id,
		$customer
	);
	//phpcs:enable WooCommerce.Commenting.CommentHooks.MissingSinceComment

	if ( '' === $last_order_id ) {
		global $wpdb;

		$order_statuses_sql = "( '" . implode( "','", array_map( 'esc_sql', array_keys( wc_get_order_statuses() ) ) ) . "' )";

		//phpcs:disable WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		if ( $this->is_cot_in_use() ) {
			$sql           = $wpdb->prepare(
				'SELECT id FROM ' . OrdersTableDataStore::get_orders_table_name() . "
				WHERE customer_id = %d
				AND status in $order_statuses_sql
				ORDER BY id DESC
				LIMIT 1",
				$customer->get_id()
			);
			$last_order_id = $wpdb->get_var( $sql );
		} else {
			$last_order_id = $wpdb->get_var(
				"SELECT posts.ID
			FROM $wpdb->posts AS posts
			LEFT JOIN {$wpdb->postmeta} AS meta on posts.ID = meta.post_id
			WHERE meta.meta_key = '_customer_user'
			AND   meta.meta_value = '" . esc_sql( $customer->get_id() ) . "'
			AND   posts.post_type = 'shop_order'
			AND   posts.post_status IN $order_statuses_sql
			ORDER BY posts.ID DESC
			LIMIT 1"
			);
		}
		//phpcs:enable WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		Users::update_site_user_meta( $customer->get_id(), 'wc_last_order', $last_order_id );
	}

	if ( ! $last_order_id ) {
		return false;
	}

	return wc_get_order( absint( $last_order_id ) );
}