Skip to content

Commit 1b39c2a

Browse files
authored
Merge pull request #4 from humanmade/elastic-blog-posts-perpage-fix
ElasticSearch Fix for Blog posts page perPage override
2 parents e62af2d + 64b3ad8 commit 1b39c2a

File tree

1 file changed

+27
-1
lines changed

1 file changed

+27
-1
lines changed

hm-query-loop.php

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,9 +201,35 @@ function pre_render_block( $pre_render, $parsed_block ) {
201201

202202
// Run the main query again to trigger the pre_get_posts hook if we're inheriting.
203203
global $wp_query;
204-
$query_args = modify_query_from_block_attrs( $wp_query->query, $attrs );
204+
205+
// On the blog posts page, $wp_query->query contains page-related args
206+
// (e.g., ['pagename' => 'blog']) instead of posts query args.
207+
// WordPress Core converts this to a posts query, but that transformation
208+
// is lost when we re-run the query. Use explicit post query args instead.
209+
if ( is_home() && ! is_front_page() ) {
210+
$query_args = [
211+
'post_type' => 'post',
212+
'paged' => $original_paged,
213+
];
214+
} else {
215+
$query_args = $wp_query->query;
216+
}
217+
218+
$query_args = modify_query_from_block_attrs( $query_args, $attrs );
219+
205220
$wp_query->query( $query_args );
206221

222+
// ElasticPress and similar plugins use posts_pre_query to return cached results,
223+
// ignoring our posts_per_page setting. Manually slice the posts array to enforce the limit.
224+
$settings = $attrs['hmQueryLoop'] ?? [];
225+
if ( isset( $settings['perPage'] ) && is_numeric( $settings['perPage'] ) && $settings['perPage'] > 0 ) {
226+
$per_page = (int) $settings['perPage'];
227+
if ( count( $wp_query->posts ) > $per_page ) {
228+
$wp_query->posts = array_slice( $wp_query->posts, 0, $per_page );
229+
$wp_query->post_count = count( $wp_query->posts );
230+
}
231+
}
232+
207233
// The global query can happen again in some cases, so avoid double collecting,
208234
// especially with AQL or similar plugins to this one.
209235
$wp_query->set( 'hm_query_loop_collect_ids', false );

0 commit comments

Comments
 (0)