Automattic\WooCommerce\Blocks\BlockTypes

ProductQuery::get_filter_by_attributes_query()privateWC 1.0

Return a query that filters products by attributes.

Method of the class: ProductQuery{}

No Hooks.

Return

Array.

Usage

// private - for code of main (parent) class only
$result = $this->get_filter_by_attributes_query();

ProductQuery::get_filter_by_attributes_query() code WC 9.4.2

private function get_filter_by_attributes_query() {
	$attributes_filter_query_args = $this->get_filter_by_attributes_query_vars();

	$queries = array_reduce(
		$attributes_filter_query_args,
		function( $acc, $query_args ) {
			$attribute_name       = $query_args['filter'];
			$attribute_query_type = $query_args['query_type'];

			$attribute_value = get_query_var( $attribute_name );
			$attribute_query = get_query_var( $attribute_query_type );

			if ( empty( $attribute_value ) ) {
				return $acc;
			}

			// It is necessary explode the value because $attribute_value can be a string with multiple values (e.g. "red,blue").
			$attribute_value = explode( ',', $attribute_value );

			$acc[] = array(
				'taxonomy' => str_replace( AttributeFilter::FILTER_QUERY_VAR_PREFIX, 'pa_', $attribute_name ),
				'field'    => 'slug',
				'terms'    => $attribute_value,
				'operator' => 'and' === $attribute_query ? 'AND' : 'IN',
			);

			return $acc;
		},
		array()
	);

	if ( empty( $queries ) ) {
		return array();
	}

	return array(
		'tax_query' => array(
			array(
				'relation' => 'AND',
				$queries,
			),
		),
	);
}