Automattic\WooCommerce\EmailEditor\Integrations\WooCommerce\Renderer\Blocks

Product_Collection::render_two_column_gridprivateWC 1.0

Render products in a two-column grid layout using HTML tables.

Method of the class: Product_Collection{}

No Hooks.

Returns

String.

Usage

// private - for code of main (parent) class only
$result = $this->render_two_column_grid( $products, $inner_block, $collection_type, $rendering_context, $block_gap ): string;
$products(array) (required)
Array of WC_Product objects.
$inner_block(array) (required)
Inner block data.
$collection_type(string) (required)
Collection type identifier.
$rendering_context(Rendering_Context) (required)
Rendering context.
$block_gap(string)
Block gap value from theme styles.
Default: '16px'

Product_Collection::render_two_column_grid() code WC 10.6.2

private function render_two_column_grid( array $products, array $inner_block, string $collection_type, Rendering_Context $rendering_context, string $block_gap = '16px' ): string {
	$content = '';

	// Calculate the cell width from the actual layout width.
	// Subtract 20px total gap (10px padding on each side of the gap between columns),
	// then divide by 2 for two columns.
	$layout_width = (int) $rendering_context->get_layout_width_without_padding();
	$gap          = 20;

	// Guard against zero or very small layout width to ensure $cell_width is always positive.
	if ( $layout_width < $gap + 2 ) {
		$layout_width = $gap + 2;
	}

	$cell_width = (int) ( ( $layout_width - $gap ) / 2 );

	$content .= '<table role="presentation" border="0" cellpadding="0" cellspacing="0" width="100%" style="width: 100%; border-collapse: collapse;">';

	$product_chunks = array_chunk( $products, 2 );

	foreach ( $product_chunks as $row_index => $row_products ) {
		$content .= '<tr>';

		foreach ( $row_products as $col_index => $product ) {
			$cell_style  = 'width: 50%; vertical-align: top; padding: 0;';
			$cell_style .= 0 === $col_index ? ' padding-right: 10px;' : ' padding-left: 10px;';

			$content .= sprintf(
				'<td style="%s">%s</td>',
				esc_attr( $cell_style ),
				$this->render_product_content( $product, $inner_block, $collection_type, $cell_width )
			);
		}

		// If odd number of products, add empty cell to complete the row.
		if ( 1 === count( $row_products ) ) {
			$content .= '<td style="width: 50%; vertical-align: top; padding: 0; padding-left: 10px;"></td>';
		}

		$content .= '</tr>';

		// Add spacing between rows (except after the last row).
		if ( $row_index < count( $product_chunks ) - 1 ) {
			$content .= sprintf( '<tr><td colspan="2" style="height: %s;"></td></tr>', esc_attr( $block_gap ) );
		}
	}

	$content .= '</table>';

	return $content;
}