Automattic\WooCommerce\Blocks\BlockTypes

ProductFilterAttribute::prepare_selected_filterspublicWC 1.0

Prepare the active filter items.

Method of the class: ProductFilterAttribute{}

No Hooks.

Returns

Array. Active filters items.

Usage

$ProductFilterAttribute = new ProductFilterAttribute();
$ProductFilterAttribute->prepare_selected_filters( $items, $params );
$items(array) (required)
The active filter items.
$params(array) (required)
The query param parsed from the URL.

ProductFilterAttribute::prepare_selected_filters() code WC 9.9.3

public function prepare_selected_filters( $items, $params ) {
	$product_attributes_map = array_reduce(
		wc_get_attribute_taxonomies(),
		function ( $acc, $attribute_object ) {
			$acc[ $attribute_object->attribute_name ] = $attribute_object->attribute_label;
			return $acc;
		},
		array()
	);

	$active_product_attributes = array_reduce(
		array_keys( $params ),
		function ( $acc, $attribute ) {
			if ( strpos( $attribute, 'filter_' ) === 0 ) {
				$acc[] = str_replace( 'filter_', '', $attribute );
			}
			return $acc;
		},
		array()
	);

	$active_product_attributes = array_filter(
		$active_product_attributes,
		function ( $item ) use ( $product_attributes_map ) {
			return in_array( $item, array_keys( $product_attributes_map ), true );
		}
	);

	foreach ( $active_product_attributes as $product_attribute ) {
		if ( empty( $params[ "filter_{$product_attribute}" ] ) || ! is_string( $params[ "filter_{$product_attribute}" ] ) ) {
			continue;
		}

		$terms                = explode( ',', $params[ "filter_{$product_attribute}" ] );
		$attribute_label      = wc_attribute_label( "pa_{$product_attribute}" );
		$attribute_query_type = $params[ "query_type_{$product_attribute}" ] ?? 'or';

		// Get attribute term by slug.
		foreach ( $terms as $term ) {
			$term_object = get_term_by( 'slug', $term, "pa_{$product_attribute}" );
			$items[]     = array(
				'type'               => 'attribute/' . $product_attribute,
				'value'              => $term,
				'activeLabel'        => "$attribute_label: $term_object->name",
				'attributeQueryType' => $attribute_query_type,
			);
		}
	}

	return $items;
}