Automattic\WooCommerce\Internal\ProductFilters

FilterData::get_attribute_countspublicWC 1.0

Get attribute counts for the current products.

Method of the class: FilterData{}

Returns

Array. termId=>count pairs.

Usage

$FilterData = new FilterData();
$FilterData->get_attribute_counts( $query_vars, $attribute_to_count );
$query_vars(array) (required)
The WP_Query arguments.
$attribute_to_count(string) (required)
Attribute taxonomy name.

FilterData::get_attribute_counts() code WC 10.7.0

public function get_attribute_counts( array $query_vars, string $attribute_to_count ) {
	/**
	 * Filter the data. @see get_filtered_price() for full documentation.
	 */
	$pre_filter_counts = apply_filters( 'woocommerce_pre_product_filter_data', null, 'attribute', $query_vars, array( 'taxonomy' => $attribute_to_count ) ); // phpcs:ignore WooCommerce.Commenting.CommentHooks.MissingSinceComment

	if ( is_array( $pre_filter_counts ) ) {
		return $pre_filter_counts;
	}

	$transient_key = $this->get_transient_key( $query_vars, 'attribute', array( 'taxonomy' => $attribute_to_count ) );
	$cached_data   = $this->get_cache( $transient_key );

	if ( ! empty( $cached_data ) ) {
		return $cached_data;
	}

	$results     = array();
	$product_ids = $this->get_cached_product_ids( $query_vars );

	if ( $product_ids ) {
		global $wpdb;

		$taxonomy_escaped    = esc_sql( wc_sanitize_taxonomy_name( $attribute_to_count ) );
		$attribute_count_sql = "
			SELECT COUNT( DISTINCT posts.ID ) as term_count, terms.term_id as term_count_id
			FROM {$wpdb->posts} AS posts
			INNER JOIN {$wpdb->term_relationships} AS term_relationships ON posts.ID = term_relationships.object_id
			INNER JOIN {$wpdb->term_taxonomy} AS term_taxonomy USING( term_taxonomy_id )
			INNER JOIN {$wpdb->terms} AS terms USING( term_id )
			WHERE posts.ID IN ( {$product_ids} )
			AND term_taxonomy.taxonomy = '{$taxonomy_escaped}'
			GROUP BY terms.term_id
		";

		/**
		 * We can't use $wpdb->prepare() here because using %s with
		 * $wpdb->prepare() for a subquery won't work as it will escape the
		 * SQL query.
		 * We're using the query as is, same as Core does.
		 */
		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
		$results = $wpdb->get_results( $attribute_count_sql );
		$results = array_map( 'absint', wp_list_pluck( $results, 'term_count', 'term_count_id' ) );
	}

	/**
	 * Filter the results. @see get_filtered_price() for full documentation.
	 *
	 * @since 9.9.0
	 */
	$results = apply_filters( 'woocommerce_product_filter_data', $results, 'attribute', $query_vars, array( 'taxonomy' => $attribute_to_count ) );

	$this->set_cache( $transient_key, $results );

	return $results;
}