Posts from Random Categories in Bricks

Updated on 31 Jul 2023

In BricksLabs Facebook group a user asked:

How would you query 3 WordPress posts from 3 different categories with Brick Builder query loop function? Case #1: the categories do not matter. Case #2: the categories matter.

This Pro tutorial provides the steps to tackle case #1 wherein we construct an array of IDs of latest posts assigned to 3 random categories in WordPress and use Bricks builder’s bricks/posts/query_vars filter to pre-filter or limit the posts output by a Bricks query loop.

Step 1

Set up a query loop and set the query type to Posts.

Do not set any other settings.

Step 2

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

add_filter( 'bricks/posts/query_vars', function( $query_vars, $settings, $element_id ) {
	if ( $element_id !== 'hbenwu' ) {
		return $query_vars;
	}

	// Get an array of IDs of 3 random categories.
	$random_categories = array_rand( array_flip( wp_list_pluck( get_categories(), 'term_id' ) ), 3 );

	// Emtpy arrays to store the post IDs and non-empty categories.
	$post_ids = [];
	$non_empty_categories = [];

	// Loop through the above category IDs and store the category ID if it has at least 1 published post.
	foreach ( $random_categories as $category_id ) {
		isset( get_category( $category_id )->count ) && $non_empty_categories[] = $category_id;
	}

	// Loop through the non-empty categories and for each, store the latest post's ID in a variable.
	foreach ( $non_empty_categories as $non_empty_category ) {
		$post_ids[] = get_posts( [
			'numberposts' => 1,
			'category' => $non_empty_category,
			'fields' => 'ids',
		] )[0];
	}

	// Remove duplicates
	$post_ids = array_unique( $post_ids );
	print( '<pre>' . print_r( $post_ids, true ) . '</pre>' );

	$query_vars['post__in'] = $post_ids;

	return $query_vars;
}, 10, 3 );

In the above replace hbenwu with the Bricks ID of your query loop element.

Note: The number of posts might be less than 3 if the random category picked does not have any posts assigned to it.