Bricks Query Loop – How to Insert Elements After Every Nth Post

Update: Follow this tutorial instead.


This Pro tutorial provides the steps to output element(s) in a Bricks‘ query loop after every nth post.

Use case: Show an ad after every 3rd post.

This is based on the previous How to Insert Element(s) Between Query Loop Posts in Bricks tutorial.

It is possible to apply display: grid to the query loop element’s parent if a grid layout is needed.

Note

This might break pagination. Implement this only for a non-paginated list of posts.

Step 1

Let’s define a couple of custom functions for getting the loop index and the modulus of loop index.

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

/**
 * Get the current loop index
 *
 * @return int
 */
function bl_get_loop_index() {
	if ( method_exists( 'BricksQuery', 'get_query_object' ) ) {
		$query_object = BricksQuery::get_query_object();

		if ( $query_object ) {
			$value = intval( $query_object::get_loop_index() ) + 1;
		}
	} else {
		$value = 0;
	}

	$value = isset( $value ) ? $value : 0;

	return $value;
}

// Function to get loop index modulus 3
function bl_get_modulus() {
   return bl_get_loop_index() % 3;
}

With the above, bl_get_modulus() will evaluate to 0 for every 3rd, 6th, 9th, 12th and so on.. posts.

Change 3 to a different number as needed.

Step 2

Edit a Page/template with Bricks.

Copy this JSON code and paste to import in the entire Section from our development site.

Ensure that “Between Posts” Block has a .between-posts class applied. Any styling should be done with this class as the active selector.

Do NOT set a custom ID for this element.

It should have this condition applied:

{echo:bl_get_modulus}

Step 3

Click on the gear icon (Settings) → PAGE SETTINGS → CUSTOM CODE → Body (footer) scripts:

<script>
document.addEventListener("DOMContentLoaded", () => {
  // move each element having a class of "between-posts" out of its parent element and as a sibling after it
  const betweenPosts = document.querySelectorAll(".between-posts")

  betweenPosts.forEach((element) => {
    element.parentNode.after(element)
  })
})
</script>

and you should be done! Check the front end.