Automattic\WooCommerce\Blocks\BlockTypes

ProductFilterAttribute::render()protectedWC 1.0

Render the block.

Method of the class: ProductFilterAttribute{}

No Hooks.

Return

String. Rendered block type output.

Usage

// protected - for code of main (parent) or child class
$result = $this->render( $attributes, $content, $block );
$attributes(array) (required)
Block attributes.
$content(string) (required)
Block content.
$block(WP_Block) (required)
Block instance.

ProductFilterAttribute::render() code WC 9.0.1

protected function render( $attributes, $content, $block ) {
	// don't render if its admin, or ajax in progress.
	if ( is_admin() || wp_doing_ajax() || empty( $attributes['attributeId'] ) ) {
		return '';
	}

	$product_attribute = wc_get_attribute( $attributes['attributeId'] );
	$attribute_counts  = $this->get_attribute_counts( $block, $product_attribute->slug, $attributes['queryType'] );

	if ( empty( $attribute_counts ) ) {
		return sprintf(
			'<div %s></div>',
			get_block_wrapper_attributes(
				array(
					'data-wc-interactive' => wp_json_encode( array( 'namespace' => $this->get_full_block_name() ) ),
					'data-has-filter'     => 'no',
				)
			),
		);
	}

	$attribute_terms = get_terms(
		array(
			'taxonomy' => $product_attribute->slug,
			'include'  => array_keys( $attribute_counts ),
		)
	);

	$selected_terms = array_filter(
		explode(
			',',
			get_query_var( 'filter_' . str_replace( 'pa_', '', $product_attribute->slug ) )
		)
	);

	$attribute_options = array_map(
		function( $term ) use ( $attribute_counts, $selected_terms ) {
			$term             = (array) $term;
			$term['count']    = $attribute_counts[ $term['term_id'] ];
			$term['selected'] = in_array( $term['slug'], $selected_terms, true );
			return $term;
		},
		$attribute_terms
	);

	$filtered_options = array_filter(
		$attribute_options,
		function( $option ) {
			return $option['count'] > 0;
		}
	);

	$filter_content = 'dropdown' === $attributes['displayStyle'] ?
		$this->render_attribute_dropdown( $filtered_options, $attributes ) :
		$this->render_attribute_checkbox_list( $filtered_options, $attributes );

	$context = array(
		'attributeSlug' => str_replace( 'pa_', '', $product_attribute->slug ),
		'queryType'     => $attributes['queryType'],
		'selectType'    => $attributes['selectType'],
	);

	return sprintf(
		'<div %1$s>%2$s%3$s</div>',
		get_block_wrapper_attributes(
			array(
				'data-wc-context'     => wp_json_encode( $context ),
				'data-wc-interactive' => wp_json_encode( array( 'namespace' => $this->get_full_block_name() ) ),
				'data-has-filter'     => 'yes',
			)
		),
		$content,
		$filter_content
	);
}