Automattic\WooCommerce\Blocks\BlockTypes

ProductFilterAttribute::get_default_product_attribute()privateWC 1.0

Get the attribute if with most term but closest to 30 terms.

Method of the class: ProductFilterAttribute{}

No Hooks.

Return

Object.

Usage

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

ProductFilterAttribute::get_default_product_attribute() code WC 9.4.2

private function get_default_product_attribute() {
	// Cache this variable in memory to prevent repeated database queries to check
	// for transient in the same request.
	static $cached = null;

	if ( $cached ) {
		return $cached;
	}

	$cached = get_transient( 'wc_block_product_filter_attribute_default_attribute' );

	if (
		$cached &&
		isset( $cached->attribute_id ) &&
		isset( $cached->attribute_name ) &&
		isset( $cached->attribute_label ) &&
		isset( $cached->attribute_type ) &&
		isset( $cached->attribute_orderby ) &&
		isset( $cached->attribute_public ) &&
		'0' !== $cached->attribute_id
	) {
		return $cached;
	}

	$attributes = wc_get_attribute_taxonomies();

	$attributes_count = array_map(
		function ( $attribute ) {
			return intval(
				wp_count_terms(
					array(
						'taxonomy'   => 'pa_' . $attribute->attribute_name,
						'hide_empty' => false,
					)
				)
			);
		},
		$attributes
	);

	asort( $attributes_count );

	$search       = 30;
	$closest      = null;
	$attribute_id = null;

	foreach ( $attributes_count as $id => $count ) {
		if ( null === $closest || abs( $search - $closest ) > abs( $count - $search ) ) {
			$closest      = $count;
			$attribute_id = $id;
		}

		if ( $closest && $count >= $search ) {
			break;
		}
	}

	$default_attribute = (object) array(
		'attribute_id'      => '0',
		'attribute_name'    => 'attribute',
		'attribute_label'   => __( 'Attribute', 'woocommerce' ),
		'attribute_type'    => 'select',
		'attribute_orderby' => 'menu_order',
		'attribute_public'  => 0,
	);

	if ( $attribute_id ) {
		$default_attribute = $attributes[ $attribute_id ];
		set_transient( 'wc_block_product_filter_attribute_default_attribute', $default_attribute, DAY_IN_SECONDS );
	}

	return $default_attribute;
}