How to Modify Products Element Query in Bricks to Output Child Products

This Pro tutorial provides the steps to limit WooCommerce products output by Bricks‘ Products element on single product pages to only the children of the current product.

Step 1

Let’s make the product post type hierarchical.

Add the following in child theme‘s functions.php or a code snippets plugin:

<?php

add_filter( 'woocommerce_register_post_type_product', function ( $args ) {
    $args['hierarchical'] = true;
    $args['supports'][] = 'page-attributes';

    return $args;
} );

Edit your products and set up parent-child arrangements as needed.

Step 2

Edit your single WooCommerce product template with Bricks.

Add a Section and inside its Container, an optional heading and Products element.

Step 3

Let’s

  1. define a custom function that returns an array of current post’s (of any post type) child posts and the count of the same
  2. hook a function to bricks/query/result filter to limit the products to only the child products on single WooCommerce product pages

Add the following in child theme‘s functions.php or a code snippets plugin:

// Function to return an array of current post's (of any post type) child posts and the count of the same
function bl_get_child_posts(): array {
	$posts_array = [];
	
	$args = array(
		'post_parent' => get_the_ID(), // current product ID
		'post_type' => get_post_type(),
		'numberposts' => -1, // retrieve all child posts
	);
	
	if ( empty( $args ) ) {
		return $posts_array;
	}
	
	return [
		'posts' => get_posts( $args ),
		'count' => count( get_posts( $args ) )
	];
}

// Limit the products to only the child products on single WooCommerce product pages
add_filter( 'bricks/query/result', function( $result, $query_obj ) {
	// Return: Element ID is not "tchley", nor is it a post query
	if ( $query_obj->element_id !== 'tchley' || $query_obj->object_type !== 'post' ) {
		return $result;
	}

	if ( $result->have_posts() ) {
		$result->posts = bl_get_child_posts()['posts'];
	}

  return $result;
}, 10, 2 );

Replace tchley with the Bricks element ID of the Products element.

Step 4

Select the Section and apply a Dynamic data condition like this:

{echo:bl_get_child_posts:array_value|count}

This ensures that the Section gets output only if there is at least 1 child product.

References

https://stackoverflow.com/a/63009156/778809

https://wordpress.stackexchange.com/a/262096

https://developer.wordpress.org/reference/functions/get_post_type/

https://academy.bricksbuilder.io/article/dynamic-data/#array_value-filter-examples