Make WordPress Core


Ignore:
Timestamp:
07/25/2025 08:35:12 AM (4 months ago)
Author:
johnbillion
Message:

Posts, Post Types: Don't unnecessarily recount terms when a post transitions between statuses that don't require them to be recounted.

This accounts for transitions where:

  • Both the old and new statuses are not included in term counts.
  • Both the old and new statuses are included in term counts.

This results in term counts only being recalculated when a post transitions between a counted and an uncounted status.

If the terms of the post are changed then the term recounting is still handled by wp_update_term_count() inside wp_set_object_terms().

Props hbhalodia, johnbillion, peterwilsoncc, mukesh27.

Fixes #63562

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/post.php

    r60365 r60510  
    81768176
    81778177    // Update counts for the post's terms.
    8178     foreach ( (array) get_object_taxonomies( $post->post_type ) as $taxonomy ) {
    8179         $tt_ids = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'tt_ids' ) );
    8180         wp_update_term_count( $tt_ids, $taxonomy );
     8178    foreach ( (array) get_object_taxonomies( $post->post_type, 'objects' ) as $taxonomy ) {
     8179        /** This filter is documented in wp-includes/taxonomy.php */
     8180        $counted_statuses = apply_filters( 'update_post_term_count_statuses', array( 'publish' ), $taxonomy );
     8181
     8182        /*
     8183         * Do not recalculate term count if both the old and new status are not included in term counts.
     8184         * This accounts for a transition such as draft -> pending.
     8185         */
     8186        if ( ! in_array( $old_status, $counted_statuses, true ) && ! in_array( $new_status, $counted_statuses, true ) ) {
     8187            continue;
     8188        }
     8189
     8190        /*
     8191         * Do not recalculate term count if both the old and new status are included in term counts.
     8192         *
     8193         * This accounts for transitioning between statuses which are both included in term counts. This can only occur
     8194         * if the `update_post_term_count_statuses` filter is in use to count more than just the 'publish' status.
     8195         */
     8196        if ( in_array( $old_status, $counted_statuses, true ) && in_array( $new_status, $counted_statuses, true ) ) {
     8197            continue;
     8198        }
     8199
     8200        $tt_ids = wp_get_object_terms( $post->ID, $taxonomy->name, array( 'fields' => 'tt_ids' ) );
     8201        wp_update_term_count( $tt_ids, $taxonomy->name );
    81818202    }
    81828203}
Note: See TracChangeset for help on using the changeset viewer.