humanmade / humanmade/altis-cms
Defer taxonomy post count calculations to background tasks for performance
- Dominant language
- PHP
- Stars
- 46
- Forks
- 4
- Avg merge
- 14h 31m
- Merged PRs (30d)
- 13
Description
When deleting, creating or updating a post it can take a long time if there's a lot of content as WordPress runs some slow queries to update the number of posts in a given taxonomy and store it in the db.
The following code can achieve this:
```php
object_type;
wp_schedule_single_event( time(), 'cron_update_taxonomy_count', [ $terms, $taxonomy->name, $object_types ] );
}
}
/**
* Update term counts, including all public stati.
*
* @param int[] $terms The term_taxonomy_ids of terms to update.
* @param string $tax_name Taxonomy name.
* @param array $object_types An array of object types.
*
* @return void
*/
function update_term_counts( $terms, string $tax_name, array $object_types ) : void {
global $wpdb;
$post_stati = get_post_stati( [ 'public' => true ] );
foreach ( array_filter( $terms ) as $term ) {
// phpcs:disable WordPress.DB.PreparedSQL.NotPrepared
$term_count = (int) $wpdb->get_var(
$wpdb->prepare(
"
SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->posts
WHERE $wpdb->posts.ID = $wpdb->term_relationships.object_id
AND post_status IN ('" . implode( "', '", $post_stati ) . "')
AND post_type IN ('" . implode( "', '", $object_types ) . "')
AND term_taxonomy_id = %d",
$term
)
);
// phpcs:enable WordPress.DB.PreparedSQL.NotPrepared
$wpdb->update( $wpdb->term_taxonomy, [ 'count' => $term_count ], [ 'term_taxonomy_id' => $term ] );
do_action( 'edited_term_taxonomy', $term, $tax_name );
}
}
```
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.