Here’s a solution that inserts ads every 5 posts without replacing them:
Add to functions.php:
add_filter( 'bricks/setup/control_options', function( $control_options ) {
$control_options['queryTypes']['gallery_with_ads'] = 'Gallery with Ads';
return $control_options;
});
add_filter( 'bricks/query/run', function( $results, $query_obj ) {
if ( $query_obj->object_type !== 'gallery_with_ads' ) {
return $results;
}
$posts_per_page = $query_obj->settings['posts_per_page'] ?? 10;
$orderby = $query_obj->settings['orderby'] ?? 'date';
$order = $query_obj->settings['order'] ?? 'DESC';
$offset = $query_obj->settings['offset'] ?? 0;
$paged = get_query_var('paged') ? get_query_var('paged') : 1;
$posts = get_posts([
'post_type' => 'gallery',
'posts_per_page' => $posts_per_page,
'post_status' => 'publish',
'orderby' => $orderby,
'order' => $order,
'offset' => $offset + (($paged - 1) * $posts_per_page),
'suppress_filters' => false
]);
$ads = get_posts([
'post_type' => 'ads',
'posts_per_page' => -1,
'post_status' => 'publish'
]);
if (empty($ads)) {
return $posts;
}
$combined_results = [];
$ad_index = 0;
foreach ($posts as $index => $post) {
$combined_results[] = $post;
if (($index + 1) % 5 === 0) {
$ad = clone $ads[$ad_index % count($ads)];
$combined_results[] = $ad;
$ad_index++;
}
}
return $combined_results;
}, 10, 2 );
add_filter( 'bricks/query/result_max_num_pages', function( $max_num_pages, $query_obj ) {
if ( $query_obj->object_type !== 'gallery_with_ads' ) {
return $max_num_pages;
}
$posts_per_page = $query_obj->settings['posts_per_page'] ?? 10;
$total_posts = wp_count_posts('post')->publish;
return ceil($total_posts / $posts_per_page);
}, 10, 2 );
In Bricks:
- Query Loop → Type: “Gallery with Ads”
- Template structure:
- Div (Gallery): Condition
{post_type} == gallery
- Div (Ad): Condition
{post_type} == ads
Both gallery and ad posts can use standard WordPress fields like {post_title}
, {post_content}
, {featured_image}
, etc.
Result: gallery1, gallery2, gallery3, gallery4, gallery5, ad1, gallery6, gallery7, gallery8, gallery9, gallery10, ad2, etc.
Note: Make sure to test thoroughly with your specific setup and pagination requirements.
Alternative: As Maexxx mentioned, you can also use the original approach with is_fifth_post - just don’t add the second condition and both divs will be shown if the HTML structure doesn’t bother you.