From b09c8c26b0c335041cd9223ea16c5528a4483e4d Mon Sep 17 00:00:00 2001 From: Rebecca Hum <16962021+rebeccahum@users.noreply.github.com> Date: Fri, 28 Jan 2022 13:19:00 -0700 Subject: [PATCH] Mirror upstream PR #2571 --- includes/classes/Indexable/Post/Post.php | 38 +++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/includes/classes/Indexable/Post/Post.php b/includes/classes/Indexable/Post/Post.php index 320a81a963..e03626d0d0 100644 --- a/includes/classes/Indexable/Post/Post.php +++ b/includes/classes/Indexable/Post/Post.php @@ -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. @@ -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 *