Automattic\WooCommerce\Admin\API

ProductsLowInStock::set_last_order_date()protectedWC 1.0

Set the last order date for each data.

Method of the class: ProductsLowInStock{}

No Hooks.

Return

Mixed.

Usage

// protected - for code of main (parent) or child class
$result = $this->set_last_order_date( $results );
$results(array)
query result from get_low_in_stock_products.
Default: array()

ProductsLowInStock::set_last_order_date() code WC 8.7.0

protected function set_last_order_date( $results = array() ) {
	global $wpdb;
	if ( 0 === count( $results ) ) {
		return $results;
	}

	$wheres = array();
	foreach ( $results as $result ) {
		'product_variation' === $result->post_type ?
			array_push( $wheres, "(product_id={$result->post_parent} and variation_id={$result->ID})" )
			: array_push( $wheres, "product_id={$result->ID}" );
	}

	count( $wheres ) ? $where_clause = implode( ' or ', $wheres ) : $where_clause = $wheres[0];

	$product_lookup_table = $wpdb->prefix . 'wc_order_product_lookup';
	$query_string         = "
		select
			product_id,
			variation_id,
			MAX( wc_order_product_lookup.date_created ) AS last_order_date
		from {$product_lookup_table} wc_order_product_lookup
		where {$where_clause}
		group by product_id
		order by date_created desc
	";

	// phpcs:ignore -- ignore prepare() warning as we're not using any user input here.
	$last_order_dates = $wpdb->get_results( $query_string );
	$last_order_dates_index = array();
	// Make an index with product_id_variation_id as a key
	// so that it can be referenced back without looping the whole array.
	foreach ( $last_order_dates as $last_order_date ) {
		$last_order_dates_index[ $last_order_date->product_id . '_' . $last_order_date->variation_id ] = $last_order_date;
	}

	foreach ( $results as &$result ) {
		'product_variation' === $result->post_type ?
			$index_key   = $result->post_parent . '_' . $result->ID
			: $index_key = $result->ID . '_' . $result->post_parent;

		if ( isset( $last_order_dates_index[ $index_key ] ) ) {
			$result->last_order_date = $last_order_dates_index[ $index_key ]->last_order_date;
		}
	}

	return $results;
}