Automattic\WooCommerce\StoreApi\Utilities

ProductQueryFilters::get_stock_status_counts()publicWC 1.0

Get stock status counts for the current products.

Method of the class: ProductQueryFilters{}

No Hooks.

Return

Array. status=>count pairs.

Usage

$ProductQueryFilters = new ProductQueryFilters();
$ProductQueryFilters->get_stock_status_counts( $request );
$request(\WP_REST_Request) (required)
The request object.

ProductQueryFilters::get_stock_status_counts() code WC 9.3.3

public function get_stock_status_counts( $request ) {
	global $wpdb;
	$product_query         = new ProductQuery();
	$stock_status_options  = array_map( 'esc_sql', array_keys( wc_get_product_stock_status_options() ) );
	$hide_outofstock_items = get_option( 'woocommerce_hide_out_of_stock_items' );
	if ( 'yes' === $hide_outofstock_items ) {
		unset( $stock_status_options['outofstock'] );
	}

	add_filter( 'posts_clauses', array( $product_query, 'add_query_clauses' ), 10, 2 );
	add_filter( 'posts_pre_query', '__return_empty_array' );

	$query_args = $product_query->prepare_objects_query( $request );
	unset( $query_args['stock_status'] );
	$query_args['no_found_rows']  = true;
	$query_args['posts_per_page'] = -1;
	$query                        = new \WP_Query();
	$result                       = $query->query( $query_args );
	$product_query_sql            = $query->request;

	remove_filter( 'posts_clauses', array( $product_query, 'add_query_clauses' ), 10 );
	remove_filter( 'posts_pre_query', '__return_empty_array' );

	$stock_status_counts = array();

	foreach ( $stock_status_options as $status ) {
		$stock_status_count_sql = $this->generate_stock_status_count_query( $status, $product_query_sql, $stock_status_options );

		$result = $wpdb->get_row( $stock_status_count_sql ); // phpcs:ignore
		$stock_status_counts[ $status ] = $result->status_count;
	}

	return $stock_status_counts;
}