Skip to content

Commit

Permalink
Mirror upstream PR 10up#2571 (#144)
Browse files Browse the repository at this point in the history
  • Loading branch information
rebeccahum authored Jan 28, 2022
1 parent 9d48e51 commit a6b141f
Showing 1 changed file with 37 additions and 1 deletion.
38 changes: 37 additions & 1 deletion includes/classes/Indexable/Post/Post.php
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ public function bulk_indexing_filter_posts_where( $where, $query ) {
* @param array $query_args The query args.
* @return int The query result's found_posts.
*/
private function get_total_objects_for_query( $query_args ) {
protected function get_total_objects_for_query( $query_args ) {
static $object_counts = [];

// Reset the pagination-related args for optimal caching.
Expand All @@ -190,9 +190,45 @@ private function get_total_objects_for_query( $query_args ) {
$object_counts[ $cache_key ] = ( new WP_Query( $normalized_query_args ) )->found_posts;
}

if ( 0 === $object_counts[ $cache_key ] ) {
// Do a DB count to make sure the query didn't just die and return 0.
$db_post_count = $this->get_total_objects_for_query_from_db( $normalized_query_args );

if ( $db_post_count !== $object_counts[ $cache_key ] ) {
$object_counts[ $cache_key ] = $db_post_count;
}
}

return $object_counts[ $cache_key ];
}

/**
* Get total posts from DB for a specific query based on it's args.
*
* @param array $query_args The query args.
* @since 4.0.0
* @return int The total posts.
*/
protected function get_total_objects_for_query_from_db( $query_args ) {
$post_count = 0;

if ( ! isset( $query_args['post_type'] ) ) {
return $post_count;
}

foreach ( $query_args['post_type'] as $post_type ) {
$post_counts_by_post_status = wp_count_posts( $post_type );
foreach ( $post_counts_by_post_status as $post_status => $post_status_count ) {
if ( ! in_array( $post_status, $query_args['post_status'], true ) ) {
continue;
}
$post_count += $post_status_count;
}
}

return $post_count;
}

/**
* Returns indexable post types for the current site
*
Expand Down

0 comments on commit a6b141f

Please sign in to comment.