Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add helper get_total_objects_for_query_from_db() which counts directly from the DB #2571

Merged
merged 3 commits into from
Jan 28, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 37 additions & 1 deletion includes/classes/Indexable/Post/Post.php
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,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 @@ -189,9 +189,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.
rebeccahum marked this conversation as resolved.
Show resolved Hide resolved
* @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