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 8.7.0

public function get_last_order( &$customer ) {
	//phpcs:disable WooCommerce.Commenting.CommentHooks.MissingSinceComment
	/**
	 * Filters the id of the last order from a given customer.
	 *
	 * @param string @last_order_id The last order id as retrieved from the database.
	 * @param WC_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',
		get_user_meta( $customer->get_id(), '_last_order', true ),
		$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
		update_user_meta( $customer->get_id(), '_last_order', $last_order_id );
	}

	if ( ! $last_order_id ) {
		return false;
	}

	return wc_get_order( absint( $last_order_id ) );
}