<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[49141] trunk: Taxonomy: Improve performance of term recounting database queries.</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { white-space: pre-line; overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta" style="font-size: 105%">
<dt style="float: left; width: 6em; font-weight: bold">Revision</dt> <dd><a style="font-weight: bold" href="https://core.trac.wordpress.org/changeset/49141">49141</a><script type="application/ld+json">{"@context":"http://schema.org","@type":"EmailMessage","description":"Review this Commit","action":{"@type":"ViewAction","url":"https://core.trac.wordpress.org/changeset/49141","name":"Review Commit"}}</script></dd>
<dt style="float: left; width: 6em; font-weight: bold">Author</dt> <dd>peterwilsoncc</dd>
<dt style="float: left; width: 6em; font-weight: bold">Date</dt> <dd>2020-10-14 00:49:52 +0000 (Wed, 14 Oct 2020)</dd>
</dl>

<pre style='padding-left: 1em; margin: 2em 0; border-left: 2px solid #ccc; line-height: 1.25; font-size: 105%; font-family: sans-serif'>Taxonomy: Improve performance of term recounting database queries.

When modifying terms assigned to an object, replace full term recounts with incrementing/decrementing the count as appropriate. This provides a significant performance boost on sites with a high number of term/object relationships and/or posts.

Introduces the functions `wp_increment_term_count()`, `wp_decrement_term_count()`, `wp_modify_term_count_by()` and `wp_modify_term_count_by_now()` for updating the term count.

Introduces the function `_wp_prevent_term_counting()` for preventing double counting on posts that are about to transition.

Adds the parameter `update_count_by_callback` to `register_taxonomy()` to allow developers to use a custom callback for incrementing or decrementing a term count.

Props boonebgorges, davidbaumwald, hellofromTonya, johnbillion, lcyh78, mattoperry, peterwilsoncc, rebasaurus, whyisjake.
Fixes <a href="https://core.trac.wordpress.org/ticket/40351">#40351</a>.</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#trunksrcwpincludesclasswptaxonomyphp">trunk/src/wp-includes/class-wp-taxonomy.php</a></li>
<li><a href="#trunksrcwpincludespostphp">trunk/src/wp-includes/post.php</a></li>
<li><a href="#trunksrcwpincludestaxonomyphp">trunk/src/wp-includes/taxonomy.php</a></li>
<li><a href="#trunktestsphpunitteststermtermCountsphp">trunk/tests/phpunit/tests/term/termCounts.php</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="trunksrcwpincludesclasswptaxonomyphp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: trunk/src/wp-includes/class-wp-taxonomy.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- trunk/src/wp-includes/class-wp-taxonomy.php       2020-10-14 00:25:43 UTC (rev 49140)
+++ trunk/src/wp-includes/class-wp-taxonomy.php 2020-10-14 00:49:52 UTC (rev 49141)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -181,6 +181,14 @@
</span><span class="cx" style="display: block; padding: 0 10px">        public $update_count_callback;
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">        /**
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         * Function that will be called when the count is modified by an amount.
+        *
+        * @since 5.6.0
+        * @var callable
+        */
+       public $update_count_by_callback;
+
+       /**
</ins><span class="cx" style="display: block; padding: 0 10px">          * Whether this taxonomy should appear in the REST API.
</span><span class="cx" style="display: block; padding: 0 10px">         *
</span><span class="cx" style="display: block; padding: 0 10px">         * Default false. If true, standard endpoints will be registered with
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -277,28 +285,29 @@
</span><span class="cx" style="display: block; padding: 0 10px">                $args = apply_filters( 'register_taxonomy_args', $args, $this->name, (array) $object_type );
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">                $defaults = array(
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                        'labels'                => array(),
-                       'description'           => '',
-                       'public'                => true,
-                       'publicly_queryable'    => null,
-                       'hierarchical'          => false,
-                       'show_ui'               => null,
-                       'show_in_menu'          => null,
-                       'show_in_nav_menus'     => null,
-                       'show_tagcloud'         => null,
-                       'show_in_quick_edit'    => null,
-                       'show_admin_column'     => false,
-                       'meta_box_cb'           => null,
-                       'meta_box_sanitize_cb'  => null,
-                       'capabilities'          => array(),
-                       'rewrite'               => true,
-                       'query_var'             => $this->name,
-                       'update_count_callback' => '',
-                       'show_in_rest'          => false,
-                       'rest_base'             => false,
-                       'rest_controller_class' => false,
-                       'default_term'          => null,
-                       '_builtin'              => false,
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                 'labels'                   => array(),
+                       'description'              => '',
+                       'public'                   => true,
+                       'publicly_queryable'       => null,
+                       'hierarchical'             => false,
+                       'show_ui'                  => null,
+                       'show_in_menu'             => null,
+                       'show_in_nav_menus'        => null,
+                       'show_tagcloud'            => null,
+                       'show_in_quick_edit'       => null,
+                       'show_admin_column'        => false,
+                       'meta_box_cb'              => null,
+                       'meta_box_sanitize_cb'     => null,
+                       'capabilities'             => array(),
+                       'rewrite'                  => true,
+                       'query_var'                => $this->name,
+                       'update_count_callback'    => '',
+                       'update_count_by_callback' => '',
+                       'show_in_rest'             => false,
+                       'rest_base'                => false,
+                       'rest_controller_class'    => false,
+                       'default_term'             => null,
+                       '_builtin'                 => false,
</ins><span class="cx" style="display: block; padding: 0 10px">                 );
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">                $args = array_merge( $defaults, $args );
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -411,6 +420,17 @@
</span><span class="cx" style="display: block; padding: 0 10px">                        );
</span><span class="cx" style="display: block; padding: 0 10px">                }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                // If generic update callback is defined but increment/decrement callback is not.
+               if (
+                       ! empty( $args['update_count_callback'] ) &&
+                       is_callable( $args['update_count_callback'] ) &&
+                       empty( $args['update_count_by_callback'] )
+               ) {
+                       $args['update_count_by_callback'] = function( $tt_ids, $taxonomy, $modify_by ) {
+                               return call_user_func( $args['update_count_callback'], $tt_ids, $taxonomy );
+                       };
+               }
+
</ins><span class="cx" style="display: block; padding: 0 10px">                 foreach ( $args as $property_name => $property_value ) {
</span><span class="cx" style="display: block; padding: 0 10px">                        $this->$property_name = $property_value;
</span><span class="cx" style="display: block; padding: 0 10px">                }
</span></span></pre></div>
<a id="trunksrcwpincludespostphp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: trunk/src/wp-includes/post.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- trunk/src/wp-includes/post.php    2020-10-14 00:25:43 UTC (rev 49140)
+++ trunk/src/wp-includes/post.php      2020-10-14 00:49:52 UTC (rev 49141)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -4071,6 +4071,8 @@
</span><span class="cx" style="display: block; padding: 0 10px">                clean_post_cache( $post_ID );
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+        // Allow term counts to be handled by transitioning post type.
+       _wp_prevent_term_counting( true );
</ins><span class="cx" style="display: block; padding: 0 10px">         if ( is_object_in_taxonomy( $post_type, 'category' ) ) {
</span><span class="cx" style="display: block; padding: 0 10px">                wp_set_post_categories( $post_ID, $post_category );
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -4127,6 +4129,8 @@
</span><span class="cx" style="display: block; padding: 0 10px">                        }
</span><span class="cx" style="display: block; padding: 0 10px">                }
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+        // Restore term counting.
+       _wp_prevent_term_counting( false );
</ins><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">        if ( ! empty( $postarr['meta_input'] ) ) {
</span><span class="cx" style="display: block; padding: 0 10px">                foreach ( $postarr['meta_input'] as $field => $value ) {
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -4436,7 +4440,9 @@
</span><span class="cx" style="display: block; padding: 0 10px">                if ( ! $default_term_id ) {
</span><span class="cx" style="display: block; padding: 0 10px">                        continue;
</span><span class="cx" style="display: block; padding: 0 10px">                }
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                _wp_prevent_term_counting( true );
</ins><span class="cx" style="display: block; padding: 0 10px">                 wp_set_post_terms( $post->ID, array( $default_term_id ), $taxonomy );
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                _wp_prevent_term_counting( false );
</ins><span class="cx" style="display: block; padding: 0 10px">         }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">        $wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post->ID ) );
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -7312,11 +7318,91 @@
</span><span class="cx" style="display: block; padding: 0 10px">  * @param WP_Post $post       Post object.
</span><span class="cx" style="display: block; padding: 0 10px">  */
</span><span class="cx" style="display: block; padding: 0 10px"> function _update_term_count_on_transition_post_status( $new_status, $old_status, $post ) {
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-        // Update counts for the post's terms.
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+ if ( 'inherit' === $new_status ) {
+               $new_status = get_post_status( $post->post_parent );
+       }
+
+       if ( 'inherit' === $old_status ) {
+               $old_status = get_post_status( $post->post_parent );
+       }
+
+       $count_new = 'publish' === $new_status;
+       $count_old = 'publish' === $old_status;
+
+       if ( $count_new === $count_old ) {
+               // Nothing to do.
+               return;
+       }
+
+       /*
+        * Update counts for the post's terms.
+        *
+        * Term counting is deferred while incrementing/decrementing the counts to
+        * reduce the number of database queries required. Once the counts are
+        * complete the updates are performed if term counting wasn't previously
+        * deferred.
+        */
+       $previous_deferred_setting = wp_defer_term_counting();
+       wp_defer_term_counting( true );
</ins><span class="cx" style="display: block; padding: 0 10px">         foreach ( (array) get_object_taxonomies( $post->post_type ) as $taxonomy ) {
</span><span class="cx" style="display: block; padding: 0 10px">                $tt_ids = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'tt_ids' ) );
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                wp_update_term_count( $tt_ids, $taxonomy );
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+
+               if ( empty( $tt_ids ) ) {
+                       // No terms for this taxonomy on object.
+                       continue;
+               }
+
+               $object_types = (array) get_taxonomy( $taxonomy )->object_type;
+
+               foreach ( $object_types as &$object_type ) {
+                       list( $object_type ) = explode( ':', $object_type );
+               }
+
+               $object_types = array_unique( $object_types );
+
+               if ( ! in_array( $post->post_type, $object_types, true ) ) {
+                       $modify_by = 0;
+               } elseif ( $count_new && ! $count_old ) {
+                       $modify_by = 1;
+               } elseif ( $count_old && ! $count_new ) {
+                       $modify_by = -1;
+               }
+
+               if ( 'attachment' === $post->post_type ) {
+                       wp_modify_term_count_by( $tt_ids, $taxonomy, $modify_by );
+                       continue;
+               }
+
+               $check_attachments = array_search( 'attachment', $object_types, true );
+               if ( false !== $check_attachments ) {
+                       unset( $object_types[ $check_attachments ] );
+                       $check_attachments = true;
+               }
+
+               wp_modify_term_count_by( $tt_ids, $taxonomy, $modify_by );
+               if ( ! $check_attachments ) {
+                       continue;
+               }
+
+               /*
+                * For non-attachments, check if there are any attachment children
+                * with 'inherited' post status -- if so those will need to be counted.
+                */
+               $attachments = get_children(
+                       array(
+                               'post_parent'            => $post->ID,
+                               'post_status'            => 'inherit',
+                               'post_type'              => 'attachment',
+                               'update_post_meta_cache' => false,
+                               'update_post_term_cache' => true,
+                       )
+               );
+
+               foreach ( $attachments as $attachment ) {
+                       _update_term_count_on_transition_post_status( $new_status, $old_status, $attachment );
+               }
</ins><span class="cx" style="display: block; padding: 0 10px">         }
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+        wp_defer_term_counting( $previous_deferred_setting );
</ins><span class="cx" style="display: block; padding: 0 10px"> }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px"> /**
</span></span></pre></div>
<a id="trunksrcwpincludestaxonomyphp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: trunk/src/wp-includes/taxonomy.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- trunk/src/wp-includes/taxonomy.php        2020-10-14 00:25:43 UTC (rev 49140)
+++ trunk/src/wp-includes/taxonomy.php  2020-10-14 00:49:52 UTC (rev 49141)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -336,6 +336,7 @@
</span><span class="cx" style="display: block; padding: 0 10px">  * @since 5.1.0 Introduced `meta_box_sanitize_cb` argument.
</span><span class="cx" style="display: block; padding: 0 10px">  * @since 5.4.0 Added the registered taxonomy object as a return value.
</span><span class="cx" style="display: block; padding: 0 10px">  * @since 5.5.0 Introduced `default_term` argument.
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+ * @since 5.6.0 Introduced `update_count_by_callback` argument.
</ins><span class="cx" style="display: block; padding: 0 10px">  *
</span><span class="cx" style="display: block; padding: 0 10px">  * @global array $wp_taxonomies Registered taxonomies.
</span><span class="cx" style="display: block; padding: 0 10px">  *
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -344,44 +345,44 @@
</span><span class="cx" style="display: block; padding: 0 10px">  * @param array|string $args        {
</span><span class="cx" style="display: block; padding: 0 10px">  *     Optional. Array or query string of arguments for registering a taxonomy.
</span><span class="cx" style="display: block; padding: 0 10px">  *
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">- *     @type array         $labels                An array of labels for this taxonomy. By default, Tag labels are
- *                                                used for non-hierarchical taxonomies, and Category labels are used
- *                                                for hierarchical taxonomies. See accepted values in
- *                                                get_taxonomy_labels(). Default empty array.
- *     @type string        $description           A short descriptive summary of what the taxonomy is for. Default empty.
- *     @type bool          $public                Whether a taxonomy is intended for use publicly either via
- *                                                the admin interface or by front-end users. The default settings
- *                                                of `$publicly_queryable`, `$show_ui`, and `$show_in_nav_menus`
- *                                                are inherited from `$public`.
- *     @type bool          $publicly_queryable    Whether the taxonomy is publicly queryable.
- *                                                If not set, the default is inherited from `$public`
- *     @type bool          $hierarchical          Whether the taxonomy is hierarchical. Default false.
- *     @type bool          $show_ui               Whether to generate and allow a UI for managing terms in this taxonomy in
- *                                                the admin. If not set, the default is inherited from `$public`
- *                                                (default true).
- *     @type bool          $show_in_menu          Whether to show the taxonomy in the admin menu. If true, the taxonomy is
- *                                                shown as a submenu of the object type menu. If false, no menu is shown.
- *                                                `$show_ui` must be true. If not set, default is inherited from `$show_ui`
- *                                                (default true).
- *     @type bool          $show_in_nav_menus     Makes this taxonomy available for selection in navigation menus. If not
- *                                                set, the default is inherited from `$public` (default true).
- *     @type bool          $show_in_rest          Whether to include the taxonomy in the REST API. Set this to true
- *                                                for the taxonomy to be available in the block editor.
- *     @type string        $rest_base             To change the base url of REST API route. Default is $taxonomy.
- *     @type string        $rest_controller_class REST API Controller class name. Default is 'WP_REST_Terms_Controller'.
- *     @type bool          $show_tagcloud         Whether to list the taxonomy in the Tag Cloud Widget controls. If not set,
- *                                                the default is inherited from `$show_ui` (default true).
- *     @type bool          $show_in_quick_edit    Whether to show the taxonomy in the quick/bulk edit panel. It not set,
- *                                                the default is inherited from `$show_ui` (default true).
- *     @type bool          $show_admin_column     Whether to display a column for the taxonomy on its post type listing
- *                                                screens. Default false.
- *     @type bool|callable $meta_box_cb           Provide a callback function for the meta box display. If not set,
- *                                                post_categories_meta_box() is used for hierarchical taxonomies, and
- *                                                post_tags_meta_box() is used for non-hierarchical. If false, no meta
- *                                                box is shown.
- *     @type callable      $meta_box_sanitize_cb  Callback function for sanitizing taxonomy data saved from a meta
- *                                                box. If no callback is defined, an appropriate one is determined
- *                                                based on the value of `$meta_box_cb`.
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+ *     @type array         $labels                   An array of labels for this taxonomy. By default, Tag labels are
+ *                                                   used for non-hierarchical taxonomies, and Category labels are used
+ *                                                   for hierarchical taxonomies. See accepted values in
+ *                                                   get_taxonomy_labels(). Default empty array.
+ *     @type string        $description              A short descriptive summary of what the taxonomy is for. Default empty.
+ *     @type bool          $public                   Whether a taxonomy is intended for use publicly either via
+ *                                                   the admin interface or by front-end users. The default settings
+ *                                                   of `$publicly_queryable`, `$show_ui`, and `$show_in_nav_menus`
+ *                                                   are inherited from `$public`.
+ *     @type bool          $publicly_queryable       Whether the taxonomy is publicly queryable.
+ *                                                   If not set, the default is inherited from `$public`
+ *     @type bool          $hierarchical             Whether the taxonomy is hierarchical. Default false.
+ *     @type bool          $show_ui                  Whether to generate and allow a UI for managing terms in this taxonomy in
+ *                                                   the admin. If not set, the default is inherited from `$public`
+ *                                                   (default true).
+ *     @type bool          $show_in_menu             Whether to show the taxonomy in the admin menu. If true, the taxonomy is
+ *                                                   shown as a submenu of the object type menu. If false, no menu is shown.
+ *                                                   `$show_ui` must be true. If not set, default is inherited from `$show_ui`
+ *                                                   (default true).
+ *     @type bool          $show_in_nav_menus        Makes this taxonomy available for selection in navigation menus. If not
+ *                                                   set, the default is inherited from `$public` (default true).
+ *     @type bool          $show_in_rest             Whether to include the taxonomy in the REST API. Set this to true
+ *                                                   for the taxonomy to be available in the block editor.
+ *     @type string        $rest_base                To change the base url of REST API route. Default is $taxonomy.
+ *     @type string        $rest_controller_class    REST API Controller class name. Default is 'WP_REST_Terms_Controller'.
+ *     @type bool          $show_tagcloud            Whether to list the taxonomy in the Tag Cloud Widget controls. If not set,
+ *                                                   the default is inherited from `$show_ui` (default true).
+ *     @type bool          $show_in_quick_edit       Whether to show the taxonomy in the quick/bulk edit panel. It not set,
+ *                                                   the default is inherited from `$show_ui` (default true).
+ *     @type bool          $show_admin_column        Whether to display a column for the taxonomy on its post type listing
+ *                                                   screens. Default false.
+ *     @type bool|callable $meta_box_cb              Provide a callback function for the meta box display. If not set,
+ *                                                   post_categories_meta_box() is used for hierarchical taxonomies, and
+ *                                                   post_tags_meta_box() is used for non-hierarchical. If false, no meta
+ *                                                   box is shown.
+ *     @type callable      $meta_box_sanitize_cb     Callback function for sanitizing taxonomy data saved from a meta
+ *                                                   box. If no callback is defined, an appropriate one is determined
+ *                                                   based on the value of `$meta_box_cb`.
</ins><span class="cx" style="display: block; padding: 0 10px">  *     @type array         $capabilities {
</span><span class="cx" style="display: block; padding: 0 10px">  *         Array of capabilities for this taxonomy.
</span><span class="cx" style="display: block; padding: 0 10px">  *
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -399,14 +400,17 @@
</span><span class="cx" style="display: block; padding: 0 10px">  *         @type bool   $hierarchical Either hierarchical rewrite tag or not. Default false.
</span><span class="cx" style="display: block; padding: 0 10px">  *         @type int    $ep_mask      Assign an endpoint mask. Default `EP_NONE`.
</span><span class="cx" style="display: block; padding: 0 10px">  *     }
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">- *     @type string|bool   $query_var             Sets the query var key for this taxonomy. Default `$taxonomy` key. If
- *                                                false, a taxonomy cannot be loaded at `?{query_var}={term_slug}`. If a
- *                                                string, the query `?{query_var}={term_slug}` will be valid.
- *     @type callable      $update_count_callback Works much like a hook, in that it will be called when the count is
- *                                                updated. Default _update_post_term_count() for taxonomies attached
- *                                                to post types, which confirms that the objects are published before
- *                                                counting them. Default _update_generic_term_count() for taxonomies
- *                                                attached to other object types, such as users.
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+ *     @type string|bool   $query_var                Sets the query var key for this taxonomy. Default `$taxonomy` key. If
+ *                                                   false, a taxonomy cannot be loaded at `?{query_var}={term_slug}`. If a
+ *                                                   string, the query `?{query_var}={term_slug}` will be valid.
+ *     @type callable      $update_count_callback    Works much like a hook, in that it will be called when the count is
+ *                                                   updated. Default _update_post_term_count() for taxonomies attached
+ *                                                   to post types, which confirms that the objects are published before
+ *                                                   counting them. Default _update_generic_term_count() for taxonomies
+ *                                                   attached to other object types, such as users.
+ *     @type callable      $update_count_by_callback Works much like a hook, in that it will be called when the count is
+ *                                                   incremented or decremented. Defaults to the value of `$update_count_callback` if
+ *                                                   a custom callack is defined, otherwise uses wp_modify_term_count_by().
</ins><span class="cx" style="display: block; padding: 0 10px">  *     @type string|array  $default_term {
</span><span class="cx" style="display: block; padding: 0 10px">  *         Default term to be used for the taxonomy.
</span><span class="cx" style="display: block; padding: 0 10px">  *
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -414,8 +418,8 @@
</span><span class="cx" style="display: block; padding: 0 10px">  *         @type string $slug         Slug for default term. Default empty.
</span><span class="cx" style="display: block; padding: 0 10px">  *         @type string $description  Description for default term. Default empty.
</span><span class="cx" style="display: block; padding: 0 10px">  *     }
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">- *     @type bool          $_builtin              This taxonomy is a "built-in" taxonomy. INTERNAL USE ONLY!
- *                                                Default false.
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+ *     @type bool          $_builtin                 This taxonomy is a "built-in" taxonomy. INTERNAL USE ONLY!
+ *                                                   Default false.
</ins><span class="cx" style="display: block; padding: 0 10px">  * }
</span><span class="cx" style="display: block; padding: 0 10px">  * @return WP_Taxonomy|WP_Error The registered taxonomy object on success, WP_Error object on failure.
</span><span class="cx" style="display: block; padding: 0 10px">  */
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -2561,6 +2565,25 @@
</span><span class="cx" style="display: block; padding: 0 10px">                return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+        $taxonomy_object = get_taxonomy( $taxonomy );
+
+       $object_types = (array) $taxonomy_object->object_type;
+       foreach ( $object_types as &$object_type ) {
+               if ( 0 === strpos( $object_type, 'attachment:' ) ) {
+                       list( $object_type ) = explode( ':', $object_type );
+               }
+       }
+
+       if ( array_filter( $object_types, 'post_type_exists' ) !== $object_types ) {
+               // This taxonomy applies to non-posts, count changes now.
+               $do_recount = ! _wp_prevent_term_counting();
+       } elseif ( 'publish' === get_post_status( $object_id ) ) {
+               // Published post, count changes now.
+               $do_recount = ! _wp_prevent_term_counting();
+       } else {
+               $do_recount = false;
+       }
+
</ins><span class="cx" style="display: block; padding: 0 10px">         if ( ! is_array( $terms ) ) {
</span><span class="cx" style="display: block; padding: 0 10px">                $terms = array( $terms );
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -2646,8 +2669,8 @@
</span><span class="cx" style="display: block; padding: 0 10px">                $new_tt_ids[] = $tt_id;
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-        if ( $new_tt_ids ) {
-               wp_update_term_count( $new_tt_ids, $taxonomy );
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+ if ( $new_tt_ids && $do_recount ) {
+               wp_increment_term_count( $new_tt_ids, $taxonomy );
</ins><span class="cx" style="display: block; padding: 0 10px">         }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">        if ( ! $append ) {
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -2665,9 +2688,7 @@
</span><span class="cx" style="display: block; padding: 0 10px">                }
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-        $t = get_taxonomy( $taxonomy );
-
-       if ( ! $append && isset( $t->sort ) && $t->sort ) {
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+ if ( ! $append && isset( $taxonomy_object->sort ) && $taxonomy_object->sort ) {
</ins><span class="cx" style="display: block; padding: 0 10px">                 $values     = array();
</span><span class="cx" style="display: block; padding: 0 10px">                $term_order = 0;
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -2748,6 +2769,31 @@
</span><span class="cx" style="display: block; padding: 0 10px">                return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+        $taxonomy_object = get_taxonomy( $taxonomy );
+
+       $object_types = (array) $taxonomy_object->object_type;
+       foreach ( $object_types as &$object_type ) {
+               if ( 0 === strpos( $object_type, 'attachment:' ) ) {
+                       list( $object_type ) = explode( ':', $object_type );
+               }
+       }
+
+       if ( array_filter( $object_types, 'post_type_exists' ) !== $object_types ) {
+               // This taxonomy applies to non-posts, count changes now.
+               $do_recount = ! _wp_prevent_term_counting();
+       } elseif (
+               'publish' === get_post_status( $object_id ) ||
+               (
+                       'inherit' === get_post_status( $object_id ) &&
+                       'publish' === get_post_status( wp_get_post_parent_id( $object_id ) )
+               )
+       ) {
+               // Published post, count changes now.
+               $do_recount = ! _wp_prevent_term_counting();
+       } else {
+               $do_recount = false;
+       }
+
</ins><span class="cx" style="display: block; padding: 0 10px">         if ( ! is_array( $terms ) ) {
</span><span class="cx" style="display: block; padding: 0 10px">                $terms = array( $terms );
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -2806,7 +2852,9 @@
</span><span class="cx" style="display: block; padding: 0 10px">                 */
</span><span class="cx" style="display: block; padding: 0 10px">                do_action( 'deleted_term_relationships', $object_id, $tt_ids, $taxonomy );
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                wp_update_term_count( $tt_ids, $taxonomy );
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         if ( $do_recount ) {
+                       wp_decrement_term_count( $tt_ids, $taxonomy );
+               }
</ins><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">                return (bool) $deleted;
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -3226,6 +3274,7 @@
</span><span class="cx" style="display: block; padding: 0 10px">                $_defer = $defer;
</span><span class="cx" style="display: block; padding: 0 10px">                // Flush any deferred counts.
</span><span class="cx" style="display: block; padding: 0 10px">                if ( ! $defer ) {
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                        wp_modify_term_count_by( null, null, null, true );
</ins><span class="cx" style="display: block; padding: 0 10px">                         wp_update_term_count( null, null, true );
</span><span class="cx" style="display: block; padding: 0 10px">                }
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -3234,6 +3283,193 @@
</span><span class="cx" style="display: block; padding: 0 10px"> }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px"> /**
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+ * Prevents add/removing a term from modifying a term count.
+ *
+ * This is used by functions calling wp_transition_post_status() to indicate the
+ * term count will be handled during the post's transition.
+ *
+ * @private
+ * @since 5.6.0
+ *
+ * @param bool $new_setting The new setting for preventing term counts.
+ * @return bool Whether term count prevention is enabled or disabled.
+ */
+function _wp_prevent_term_counting( $new_setting = null ) {
+       static $prevent = false;
+
+       if ( is_bool( $new_setting ) ) {
+               $prevent = $new_setting;
+       }
+
+       return $prevent;
+}
+
+/**
+ * Increments the amount of terms in taxonomy.
+ *
+ * If there is a taxonomy callback applied, then it will be called for updating
+ * the count.
+ *
+ * The default action is to increment the count by one and update the database.
+ *
+ * @since 5.6.0
+ *
+ * @param int|array $tt_ids       The term_taxonomy_id of the terms.
+ * @param string    $taxonomy     The context of the term.
+ * @param int       $increment_by By how many the term count is to be incremented. Default 1.
+ * @param bool      $do_deferred  Whether to flush the deferred term counts too. Default false.
+ * @return bool If no terms will return false, and if successful will return true.
+ */
+function wp_increment_term_count( $tt_ids, $taxonomy, $increment_by = 1, $do_deferred = false ) {
+       return wp_modify_term_count_by( $tt_ids, $taxonomy, $increment_by, $do_deferred );
+}
+
+/**
+ * Decrements the amount of terms in taxonomy.
+ *
+ * If there is a taxonomy callback applied, then it will be called for updating
+ * the count.
+ *
+ * The default action is to decrement the count by one and update the database.
+ *
+ * @since 5.6.0
+ *
+ * @param int|array $tt_ids       The term_taxonomy_id of the terms.
+ * @param string    $taxonomy     The context of the term.
+ * @param int       $decrement_by By how many the term count is to be decremented. Default 1.
+ * @param bool      $do_deferred  Whether to flush the deferred term counts too. Default false.
+ * @return bool If no terms will return false, and if successful will return true.
+ */
+function wp_decrement_term_count( $tt_ids, $taxonomy, $decrement_by = 1, $do_deferred = false ) {
+       return wp_modify_term_count_by( $tt_ids, $taxonomy, $decrement_by * -1, $do_deferred );
+}
+
+/**
+ * Modifies the amount of terms in taxonomy.
+ *
+ * If there is a taxonomy callback applied, then it will be called for updating
+ * the count.
+ *
+ * The default action is to decrement the count by one and update the database.
+ *
+ * @since 5.6.0
+ *
+ * @param int|array $tt_ids      The term_taxonomy_id of the terms.
+ * @param string    $taxonomy    The context of the term.
+ * @param int       $modify_by   By how many the term count is to be modified.
+ * @param bool      $do_deferred Whether to flush the deferred term counts too. Default false.
+ * @return bool If no terms will return false, and if successful will return true.
+ */
+function wp_modify_term_count_by( $tt_ids, $taxonomy, $modify_by, $do_deferred = false ) {
+       static $_deferred = array();
+
+       if ( $do_deferred ) {
+               foreach ( (array) $_deferred as $taxonomy_name => $modifications ) {
+                       $tax_by_count = array_reduce(
+                               array_keys( $modifications ),
+                               function( $by_count, $tt_id ) use ( $modifications ) {
+                                       if ( ! isset( $by_count[ $modifications[ $tt_id ] ] ) ) {
+                                               $by_count[ $modifications[ $tt_id ] ] = array();
+                                       }
+                                       $by_count[ $modifications[ $tt_id ] ][] = $tt_id;
+                                       return $by_count;
+                               },
+                               array()
+                       );
+
+                       foreach ( $tax_by_count as $_modify_by => $_tt_ids ) {
+                               wp_modify_term_count_by_now( $_tt_ids, $taxonomy_name, $_modify_by );
+                       }
+                       unset( $_deferred[ $taxonomy_name ] );
+               }
+       }
+
+       if ( empty( $tt_ids ) ) {
+               return false;
+       }
+
+       if ( ! is_array( $tt_ids ) ) {
+               $tt_ids = array( $tt_ids );
+       }
+
+       if ( wp_defer_term_counting() ) {
+               foreach ( $tt_ids as $tt_id ) {
+                       if ( ! isset( $_deferred[ $taxonomy ][ $tt_id ] ) ) {
+                               $_deferred[ $taxonomy ][ $tt_id ] = 0;
+                       }
+                       $_deferred[ $taxonomy ][ $tt_id ] += $modify_by;
+               }
+               return true;
+       }
+
+       return wp_modify_term_count_by_now( $tt_ids, $taxonomy, $modify_by );
+}
+
+/**
+ * Modifies the amount of terms in taxonomy immediately
+ *
+ * If there is a taxonomy callback applied, then it will be called for updating
+ * the count.
+ *
+ * The default action is to decrement the count by one and update the database.
+ *
+ * @since 5.6.0
+ *
+ * @param int|array $tt_ids      The term_taxonomy_id of the terms.
+ * @param string    $taxonomy    The context of the term.
+ * @param int       $modify_by   By how many the term count is to be modified.
+ * @return bool If no terms will return false, and if successful will return true.
+ */
+function wp_modify_term_count_by_now( $tt_ids, $taxonomy, $modify_by ) {
+       global $wpdb;
+
+       if ( 0 === $modify_by ) {
+               return false;
+       }
+
+       $tt_ids = array_filter( array_map( 'intval', (array) $tt_ids ) );
+
+       if ( empty( $tt_ids ) ) {
+               return false;
+       }
+
+       $taxonomy = get_taxonomy( $taxonomy );
+       if ( ! empty( $taxonomy->update_count_by_callback ) ) {
+               call_user_func( $taxonomy->update_count_by_callback, $tt_ids, $taxonomy, $modify_by );
+               clean_term_cache( $tt_ids, '', false );
+               return true;
+       }
+
+       $tt_ids_string = '(' . implode( ',', $tt_ids ) . ')';
+
+       foreach ( $tt_ids as $tt_id ) {
+               /** This action is documented in wp-includes/taxonomy.php */
+               do_action( 'edit_term_taxonomy', $tt_id, $taxonomy );
+       }
+
+       $result = $wpdb->query(
+               $wpdb->prepare(
+                       // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
+                       "UPDATE {$wpdb->term_taxonomy} AS tt SET tt.count = GREATEST( 0, tt.count + %d ) WHERE tt.term_taxonomy_id IN $tt_ids_string",
+                       $modify_by
+               )
+       );
+
+       if ( ! $result ) {
+               return false;
+       }
+
+       foreach ( $tt_ids as $tt_id ) {
+               /** This action is documented in wp-includes/taxonomy.php */
+               do_action( 'edited_term_taxonomy', $tt_id, $taxonomy );
+       }
+
+       clean_term_cache( $tt_ids, '', false );
+
+       return true;
+}
+
+/**
</ins><span class="cx" style="display: block; padding: 0 10px">  * Updates the amount of terms in taxonomy.
</span><span class="cx" style="display: block; padding: 0 10px">  *
</span><span class="cx" style="display: block; padding: 0 10px">  * If there is a taxonomy callback applied, then it will be called for updating
</span></span></pre></div>
<a id="trunktestsphpunitteststermtermCountsphp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: trunk/tests/phpunit/tests/term/termCounts.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- trunk/tests/phpunit/tests/term/termCounts.php     2020-10-14 00:25:43 UTC (rev 49140)
+++ trunk/tests/phpunit/tests/term/termCounts.php       2020-10-14 00:49:52 UTC (rev 49141)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -20,6 +20,27 @@
</span><span class="cx" style="display: block; padding: 0 10px">        public static $post_ids;
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">        /**
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         * Array of tag IDs.
+        *
+        * @var int[]
+        */
+       public static $tag_ids;
+
+       /**
+        * Term ID for testing user counts.
+        *
+        * @var int
+        */
+       public static $user_term;
+
+       /**
+        * User ID for testing user counts.
+        *
+        * @var int
+        */
+       public static $user_id;
+
+       /**
</ins><span class="cx" style="display: block; padding: 0 10px">          * Create shared fixtures.
</span><span class="cx" style="display: block; padding: 0 10px">         *
</span><span class="cx" style="display: block; padding: 0 10px">         * @param WP_UnitTest_Factory $factory Test suite factory.
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -30,21 +51,78 @@
</span><span class="cx" style="display: block; padding: 0 10px">                        self::$post_ids[ $status ] = $factory->post->create( array( 'post_status' => $status ) );
</span><span class="cx" style="display: block; padding: 0 10px">                }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                register_taxonomy( 'wp_test_tax_counts', array( 'post', 'attachment' ) );
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         // Extra published post.
+               self::$post_ids['publish_two'] = $factory->post->create( array( 'post_status' => 'publish' ) );
+
+               self::$user_id = $factory->user->create( array( 'role' => 'author' ) );
+
+               self::register_taxonomies();
</ins><span class="cx" style="display: block; padding: 0 10px">                 self::$attachment_term = $factory->term->create( array( 'taxonomy' => 'wp_test_tax_counts' ) );
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                self::$user_term       = $factory->term->create( array( 'taxonomy' => 'wp_test_user_tax_counts' ) );
+               self::$tag_ids         = $factory->term->create_many( 5 );
</ins><span class="cx" style="display: block; padding: 0 10px">         }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">        public function setUp() {
</span><span class="cx" style="display: block; padding: 0 10px">                parent::setUp();
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                self::register_taxonomies();
+       }
</ins><span class="cx" style="display: block; padding: 0 10px"> 
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+        /**
+        * Register taxonomies used by tests.
+        *
+        * This is called both before class and before each test as the global is
+        * reset in each test's tearDown.
+        */
+       public static function register_taxonomies() {
</ins><span class="cx" style="display: block; padding: 0 10px">                 register_taxonomy( 'wp_test_tax_counts', array( 'post', 'attachment' ) );
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                register_taxonomy( 'wp_test_user_tax_counts', 'user' );
</ins><span class="cx" style="display: block; padding: 0 10px">         }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">        /**
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         * Term counts are not double incremented when post created.
+        *
+        * @covers wp_modify_term_count_by
+        * @dataProvider data_term_count_changes_for_post_statuses
+        * @ticket 40351
+        *
+        * @param string $post_status New post status.
+        * @param int    $change      Expected change.
+        */
+       public function test_term_count_changes_for_post_statuses( $post_status, $change ) {
+               $term_count = get_term( get_option( 'default_category' ) )->count;
+               // Do not use shared fixture for this test as it relies on a new post.
+               $post_id = $this->factory()->post->create( array( 'post_status' => $post_status ) );
+
+               $expected = $term_count + $change;
+               $this->assertSame( $expected, get_term( get_option( 'default_category' ) )->count );
+       }
+
+       /**
+        * Data provider for test_term_count_changes_for_post_statuses.
+        *
+        * @return array[] {
+        *     @type string $post_status New post status.
+        *     @type int    $change      Expected change.
+        * }
+        */
+       function data_term_count_changes_for_post_statuses() {
+               return array(
+                       // 0. Published post
+                       array( 'publish', 1 ),
+                       // 1. Auto draft
+                       array( 'auto-draft', 0 ),
+                       // 2. Draft
+                       array( 'draft', 0 ),
+                       // 3. Private post
+                       array( 'private', 0 ),
+               );
+       }
+
+       /**
</ins><span class="cx" style="display: block; padding: 0 10px">          * Term counts increments correctly when post status becomes published.
</span><span class="cx" style="display: block; padding: 0 10px">         *
</span><span class="cx" style="display: block; padding: 0 10px">         * @covers wp_publish_post
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-         * @covers wp_count_terms
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+  * @covers wp_modify_term_count_by
</ins><span class="cx" style="display: block; padding: 0 10px">          * @dataProvider data_term_counts_incremented_on_publish
</span><span class="cx" style="display: block; padding: 0 10px">         * @ticket 40351
</span><span class="cx" style="display: block; padding: 0 10px">         * @ticket 51292
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -84,9 +162,125 @@
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">        /**
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         * Test post status transition update term counts correctly.
+        *
+        * @covers wp_modify_term_count_by
+        * @dataProvider data_term_count_transitions_update_term_counts
+        * @ticket 40351
+        *
+        * @param string $original_post_status Post status upon create.
+        * @param string $new_post_status      Post status after update.
+        * @param int    $change               Expected change upon publish.
+        */
+       function test_term_count_transitions_update_term_counts( $original_post_status, $new_post_status, $change ) {
+               $post_id    = self::$post_ids[ $original_post_status ];
+               $term_count = get_term( get_option( 'default_category' ) )->count;
+
+               wp_update_post(
+                       array(
+                               'ID'          => $post_id,
+                               'post_status' => $new_post_status,
+                       )
+               );
+
+               $expected = $term_count + $change;
+               $this->assertSame( $expected, get_term( get_option( 'default_category' ) )->count );
+       }
+
+       /**
+        * Data provider for test_term_count_transitions_update_term_counts.
+        *
+        * @return array[] {
+        *     @type string $original_post_status Post status upon create.
+        *     @type string $new_post_status      Post status after update.
+        *     @type int    $change               Expected change upon publish.
+        * }
+        */
+       function data_term_count_transitions_update_term_counts() {
+               return array(
+                       // 0. Draft -> published post
+                       array( 'draft', 'publish', 1 ),
+                       // 1. Auto draft -> published post
+                       array( 'auto-draft', 'publish', 1 ),
+                       // 2. Private -> published post
+                       array( 'private', 'publish', 1 ),
+                       // 3. Published -> published post
+                       array( 'publish', 'publish', 0 ),
+
+                       // 4. Draft -> private post
+                       array( 'draft', 'private', 0 ),
+                       // 5. Auto draft -> private post
+                       array( 'auto-draft', 'private', 0 ),
+                       // 6. Private -> private post
+                       array( 'private', 'private', 0 ),
+                       // 7. Published -> private post
+                       array( 'publish', 'private', -1 ),
+
+                       // 8. Draft -> draft post
+                       array( 'draft', 'draft', 0 ),
+                       // 9. Auto draft -> draft post
+                       array( 'auto-draft', 'draft', 0 ),
+                       // 10. Private -> draft post
+                       array( 'private', 'draft', 0 ),
+                       // 11. Published -> draft post
+                       array( 'publish', 'draft', -1 ),
+               );
+       }
+
+       /**
+        * Term counts are not double incremented when post created.
+        *
+        * @covers wp_modify_term_count_by
+        * @dataProvider data_term_count_changes_for_post_statuses_with_attachments
+        * @ticket 40351
+        *
+        * @param string $post_status New post status.
+        * @param int    $change      Expected change.
+        */
+       public function test_term_count_changes_for_post_statuses_with_attachments( $post_status, $change ) {
+               $term_count = get_term( self::$attachment_term )->count;
+               // Do not use shared fixture for this test as it relies on a new post.
+               $post_id = $this->factory()->post->create( array( 'post_status' => $post_status ) );
+               wp_add_object_terms( $post_id, self::$attachment_term, 'wp_test_tax_counts' );
+               $attachment_id = self::factory()->attachment->create_object(
+                       array(
+                               'file'        => 'image.jpg',
+                               'post_parent' => $post_id,
+                               'post_status' => 'inherit',
+                       )
+               );
+               wp_add_object_terms( $attachment_id, self::$attachment_term, 'wp_test_tax_counts' );
+
+               $expected = $term_count + $change;
+               $this->assertSame( $expected, get_term( self::$attachment_term )->count );
+       }
+
+       /**
+        * Data provider for test_term_count_changes_for_post_statuses_with_attachments.
+        *
+        * @return array[] {
+        *     @type string $post_status New post status.
+        *     @type int    $change      Expected change.
+        * }
+        */
+       function data_term_count_changes_for_post_statuses_with_attachments() {
+               return array(
+                       // 0. Published post
+                       array( 'publish', 2 ),
+                       // 1. Auto draft
+                       array( 'auto-draft', 0 ),
+                       // 2. Draft
+                       array( 'draft', 0 ),
+                       // 3. Private post
+                       array( 'private', 0 ),
+               );
+       }
+
+       /**
</ins><span class="cx" style="display: block; padding: 0 10px">          * Term counts increments correctly when post status becomes published.
</span><span class="cx" style="display: block; padding: 0 10px">         *
</span><span class="cx" style="display: block; padding: 0 10px">         * @covers wp_publish_post
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         * @covers wp_modify_term_count_by
</ins><span class="cx" style="display: block; padding: 0 10px">          * @dataProvider data_term_counts_incremented_on_publish_with_attachments
</span><span class="cx" style="display: block; padding: 0 10px">         * @ticket 40351
</span><span class="cx" style="display: block; padding: 0 10px">         * @ticket 51292
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -135,8 +329,132 @@
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">        /**
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         * Test post status transition update term counts correctly.
+        *
+        * @covers wp_modify_term_count_by
+        * @dataProvider data_term_count_transitions_update_term_counts_with_attachments
+        * @ticket 40351
+        *
+        * @param string $original_post_status Post status upon create.
+        * @param string $new_post_status      Post status after update.
+        * @param int    $change               Expected change upon publish.
+        */
+       function test_term_count_transitions_update_term_counts_with_attachments( $original_post_status, $new_post_status, $change ) {
+               $post_id = self::$post_ids[ $original_post_status ];
+               wp_add_object_terms( $post_id, self::$attachment_term, 'wp_test_tax_counts' );
+               $attachment_id = self::factory()->attachment->create_object(
+                       array(
+                               'file'        => 'image.jpg',
+                               'post_parent' => $post_id,
+                               'post_status' => 'inherit',
+                       )
+               );
+               wp_add_object_terms( $attachment_id, self::$attachment_term, 'wp_test_tax_counts' );
+               $term_count = get_term( self::$attachment_term )->count;
+
+               wp_update_post(
+                       array(
+                               'ID'          => $post_id,
+                               'post_status' => $new_post_status,
+                       )
+               );
+
+               $expected = $term_count + $change;
+               $this->assertSame( $expected, get_term( self::$attachment_term )->count );
+       }
+
+       /**
+        * Data provider for test_term_count_transitions_update_term_counts_with_attachments.
+        *
+        * @return array[] {
+        *     @type string $original_post_status Post status upon create.
+        *     @type string $new_post_status      Post status after update.
+        *     @type int    $change               Expected change upon publish.
+        * }
+        */
+       function data_term_count_transitions_update_term_counts_with_attachments() {
+               return array(
+                       // 0. Draft -> published post
+                       array( 'draft', 'publish', 2 ),
+                       // 1. Auto draft -> published post
+                       array( 'auto-draft', 'publish', 2 ),
+                       // 2. Private -> published post
+                       array( 'private', 'publish', 2 ),
+                       // 3. Published -> published post
+                       array( 'publish', 'publish', 0 ),
+
+                       // 4. Draft -> private post
+                       array( 'draft', 'private', 0 ),
+                       // 5. Auto draft -> private post
+                       array( 'auto-draft', 'private', 0 ),
+                       // 6. Private -> private post
+                       array( 'private', 'private', 0 ),
+                       // 7. Published -> private post
+                       array( 'publish', 'private', -2 ),
+
+                       // 8. Draft -> draft post
+                       array( 'draft', 'draft', 0 ),
+                       // 9. Auto draft -> draft post
+                       array( 'auto-draft', 'draft', 0 ),
+                       // 10. Private -> draft post
+                       array( 'private', 'draft', 0 ),
+                       // 11. Published -> draft post
+                       array( 'publish', 'draft', -2 ),
+               );
+       }
+
+       /**
+        * Term counts are not double incremented when post created.
+        *
+        * @covers wp_modify_term_count_by
+        * @dataProvider data_term_count_changes_for_post_statuses_with_untermed_attachments
+        * @ticket 40351
+        *
+        * @param string $post_status New post status.
+        * @param int    $change      Expected change.
+        */
+       public function test_term_count_changes_for_post_statuses_with_untermed_attachments( $post_status, $change ) {
+               $term_count = get_term( self::$attachment_term )->count;
+               // Do not use shared fixture for this test as it relies on a new post.
+               $post_id = $this->factory()->post->create( array( 'post_status' => $post_status ) );
+               wp_add_object_terms( $post_id, self::$attachment_term, 'wp_test_tax_counts' );
+               $attachment_id = self::factory()->attachment->create_object(
+                       array(
+                               'file'        => 'image.jpg',
+                               'post_parent' => $post_id,
+                               'post_status' => 'inherit',
+                       )
+               );
+
+               $expected = $term_count + $change;
+               $this->assertSame( $expected, get_term( self::$attachment_term )->count );
+       }
+
+       /**
+        * Data provider for test_term_count_changes_for_post_statuses_with_untermed_attachments.
+        *
+        * @return array[] {
+        *     @type string $post_status New post status.
+        *     @type int    $change      Expected change.
+        * }
+        */
+       function data_term_count_changes_for_post_statuses_with_untermed_attachments() {
+               return array(
+                       // 0. Published post
+                       array( 'publish', 1 ),
+                       // 1. Auto draft
+                       array( 'auto-draft', 0 ),
+                       // 2. Draft
+                       array( 'draft', 0 ),
+                       // 3. Private post
+                       array( 'private', 0 ),
+               );
+       }
+
+       /**
</ins><span class="cx" style="display: block; padding: 0 10px">          * Term counts increments correctly when post status becomes published.
</span><span class="cx" style="display: block; padding: 0 10px">         *
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         * @covers wp_modify_term_count_by
</ins><span class="cx" style="display: block; padding: 0 10px">          * @covers wp_publish_post
</span><span class="cx" style="display: block; padding: 0 10px">         * @dataProvider data_term_counts_incremented_on_publish_with_untermed_attachments
</span><span class="cx" style="display: block; padding: 0 10px">         * @ticket 40351
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -183,4 +501,195 @@
</span><span class="cx" style="display: block; padding: 0 10px">                        array( 'private', 1 ),
</span><span class="cx" style="display: block; padding: 0 10px">                );
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+
+       /**
+        * Test post status transition update term counts correctly.
+        *
+        * @covers wp_modify_term_count_by
+        * @dataProvider data_term_count_transitions_update_term_counts_with_untermed_attachments
+        * @ticket 40351
+        *
+        * @param string $original_post_status Post status upon create.
+        * @param string $new_post_status      Post status after update.
+        * @param int    $change               Expected change upon publish.
+        */
+       function test_term_count_transitions_update_term_counts_with_untermed_attachments( $original_post_status, $new_post_status, $change ) {
+               $post_id = self::$post_ids[ $original_post_status ];
+               wp_add_object_terms( $post_id, self::$attachment_term, 'wp_test_tax_counts' );
+               $attachment_id = self::factory()->attachment->create_object(
+                       array(
+                               'file'        => 'image.jpg',
+                               'post_parent' => $post_id,
+                               'post_status' => 'inherit',
+                       )
+               );
+               $term_count    = get_term( self::$attachment_term )->count;
+
+               wp_update_post(
+                       array(
+                               'ID'          => $post_id,
+                               'post_status' => $new_post_status,
+                       )
+               );
+
+               $expected = $term_count + $change;
+               $this->assertSame( $expected, get_term( self::$attachment_term )->count );
+       }
+
+       /**
+        * Data provider for test_term_count_transitions_update_term_counts_with_untermed_attachments.
+        *
+        * @return array[] {
+        *     @type string $original_post_status Post status upon create.
+        *     @type string $new_post_status      Post status after update.
+        *     @type int    $change               Expected change upon publish.
+        * }
+        */
+       function data_term_count_transitions_update_term_counts_with_untermed_attachments() {
+               return array(
+                       // 0. Draft -> published post
+                       array( 'draft', 'publish', 1 ),
+                       // 1. Auto draft -> published post
+                       array( 'auto-draft', 'publish', 1 ),
+                       // 2. Private -> published post
+                       array( 'private', 'publish', 1 ),
+                       // 3. Published -> published post
+                       array( 'publish', 'publish', 0 ),
+
+                       // 4. Draft -> private post
+                       array( 'draft', 'private', 0 ),
+                       // 5. Auto draft -> private post
+                       array( 'auto-draft', 'private', 0 ),
+                       // 6. Private -> private post
+                       array( 'private', 'private', 0 ),
+                       // 7. Published -> private post
+                       array( 'publish', 'private', -1 ),
+
+                       // 8. Draft -> draft post
+                       array( 'draft', 'draft', 0 ),
+                       // 9. Auto draft -> draft post
+                       array( 'auto-draft', 'draft', 0 ),
+                       // 10. Private -> draft post
+                       array( 'private', 'draft', 0 ),
+                       // 11. Published -> draft post
+                       array( 'publish', 'draft', -1 ),
+               );
+       }
+
+       /**
+        * User taxonomy term counts increments when added to an account.
+        *
+        * @covers wp_modify_term_count_by
+        * @ticket 51292
+        */
+       public function test_term_counts_user_adding_term() {
+               $term_count = get_term( self::$user_term )->count;
+               wp_add_object_terms( self::$user_id, self::$user_term, 'wp_test_user_tax_counts' );
+
+               $expected = $term_count + 1;
+               $this->assertSame( $expected, get_term( self::$user_term )->count );
+       }
+
+       /**
+        * User taxonomy term counts decrement when term deleted from user.
+        *
+        * @covers wp_modify_term_count_by
+        * @ticket 51292
+        */
+       public function test_term_counts_user_removing_term() {
+               wp_add_object_terms( self::$user_id, self::$user_term, 'wp_test_user_tax_counts' );
+               $term_count = get_term( self::$user_term )->count;
+
+               wp_remove_object_terms( self::$user_id, self::$user_term, 'wp_test_user_tax_counts' );
+               $expected = $term_count - 1;
+               $this->assertSame( $expected, get_term( self::$user_term )->count );
+       }
+
+       /**
+        * Ensure DB queries for deferred counts are nullified for net zero gain.
+        *
+        * @covers wp_modify_term_count_by
+        * @covers wp_defer_term_counting
+        * @ticket 51292
+        */
+       public function test_counts_after_deferral_net_zero() {
+               $post_one = self::$post_ids['publish'];
+               $post_two = self::$post_ids['publish_two'];
+               $terms    = self::$tag_ids;
+
+               wp_set_object_terms( $post_one, $terms[0], 'post_tag', true );
+
+               // Net gain 0;
+               wp_defer_term_counting( true );
+               wp_remove_object_terms( $post_one, $terms[0], 'post_tag' );
+               wp_set_object_terms( $post_two, $terms[0], 'post_tag', true );
+               $num_queries = get_num_queries();
+               wp_defer_term_counting( false );
+               // Ensure number of queries unchanged.
+               $this->assertSame( $num_queries, get_num_queries() );
+       }
+
+       /**
+        * Ensure full recounts follow modify by X recounts to avoid miscounts.
+        *
+        * @covers wp_modify_term_count_by
+        * @covers wp_update_term_count
+        * @covers wp_defer_term_counting
+        * @ticket 51292
+        */
+       public function test_counts_after_deferral_full_before_partial() {
+               $post_one   = self::$post_ids['publish'];
+               $terms      = self::$tag_ids;
+               $term_count = get_term( $terms[0] )->count;
+
+               // Net gain 1;
+               wp_defer_term_counting( true );
+               wp_set_object_terms( $post_one, $terms[0], 'post_tag', true );
+               wp_update_term_count( get_term( $terms[0] )->term_taxonomy_id, 'post_tag' );
+               wp_defer_term_counting( false );
+
+               // Ensure term count is correct.
+               $expected = $term_count + 1;
+               $this->assertSame( $expected, get_term( $terms[0] )->count );
+       }
+
+       /**
+        * Ensure DB queries for deferred counts are combined.
+        *
+        * @covers wp_modify_term_count_by
+        * @covers wp_defer_term_counting
+        * @ticket 51292
+        */
+       public function test_counts_after_deferral_matching_changes() {
+               $post_one = self::$post_ids['publish'];
+               $post_two = self::$post_ids['publish_two'];
+               $terms    = self::$tag_ids;
+
+               wp_set_object_terms( $post_one, $terms[0], 'post_tag', true );
+
+               // Net gain 0:
+               wp_defer_term_counting( true );
+               wp_remove_object_terms( $post_one, $terms[0], 'post_tag' );
+               wp_set_object_terms( $post_two, $terms[0], 'post_tag', true );
+
+               // Net gain 1:
+               wp_set_object_terms( $post_one, $terms[1], 'post_tag', true );
+               wp_set_object_terms( $post_two, $terms[2], 'post_tag', true );
+
+               // Net gain 2:
+               wp_set_object_terms( $post_one, array( $terms[3], $terms[4] ), 'post_tag', true );
+               wp_set_object_terms( $post_two, array( $terms[3], $terms[4] ), 'post_tag', true );
+
+               $num_queries = get_num_queries();
+               wp_defer_term_counting( false );
+
+               /*
+                * Each count is expected to produce two queries:
+                * 1) The count update
+                * 2) The SELECT in `clean_term_cache()`.
+                */
+               $expected = $num_queries + ( 2 * 2 );
+               // Ensure number of queries correct.
+               $this->assertSame( $expected, get_num_queries() );
+       }
</ins><span class="cx" style="display: block; padding: 0 10px"> }
</span></span></pre>
</div>
</div>

</body>
</html>