Skip to content

Instantly share code, notes, and snippets.

@rumur
Last active February 2, 2019 19:48
Show Gist options
  • Save rumur/c3f7adb9c6d456e47ed9a9d4bd012779 to your computer and use it in GitHub Desktop.
Save rumur/c3f7adb9c6d456e47ed9a9d4bd012779 to your computer and use it in GitHub Desktop.
Update WordPress taxonomies(categories/tags) count field
<?php
/**
* Adds the button to the Category Screen and allows to reindex the Terms post count.
*
* @since v1.0 - 15.06.2018
*
* @author rumur
*/
add_action('current_screen', function($current_screen) {
if (in_array($current_screen->base, ['edit-tags']) ) {
add_action('admin_notices', function () use ($current_screen) {
try {
$notice_class = array(
'notice',
'notice-info', // blue
//'notice-error' // red
//'notice-warning' // yellow/orange
//'notice-success' // green
);
$html = '<div class="%1$s"><p><strong>%2$s</strong></p></div>';
$btn = sprintf('<span class="spinner"></span><button class="button button-primary"
data-post_type="%2$s"
data-taxonomy="%3$s"
onclick="reIndexPostCount(this)"
>%1$s</button>',
__('Reindex?', 'rumur'),
$current_screen->post_type,
$current_screen->taxonomy
);
$nonce = wp_create_nonce('reindex-post-count');
$patient = __('Be patient, we are working on it.', 'rumur');
$script = "
<script type=\"text/javascript\">
var ReIndexInProgress = false;
function reIndexPostCount(btn) {
try {
var spinner = btn.previousSibling;
if (ReIndexInProgress) {
alert('{$patient}');
} else {
ReIndexInProgress = true;
spinner.classList.toggle('is-active', ReIndexInProgress);
wp.ajax.post('fix_taxonomy_count', {
_ajax_nonce: '{$nonce}',
post_type: btn.dataset.post_type,
taxonomy: btn.dataset.taxonomy,
}).done( function( response ) {
ReIndexInProgress = false;
spinner.classList.toggle('is-active', ReIndexInProgress);
if (confirm(response)) {
window.location.reload();
}
}).fail(function(response) {
ReIndexInProgress = false;
spinner.classList.toggle('is-active', ReIndexInProgress);
alert(response);
});
}
} catch (e) {
console.error('Category Reindexer:: ', e);
}
}
</script>
";
$message = [
$script,
sprintf(__('Do you want to reindex %s posts count?', 'rumur'), get_taxonomy($current_screen->taxonomy)->label),
$btn,
];
printf($html, join(' ', $notice_class), join(' ', $message));
} catch (Throwable $e) {
error_log('< Taxonomy count reindexer > ' . $e->getMessage());
}
});
}
});
/**
* Re indexer AJAX handler.
*
* @since v1.0 - 15.05.2018
*
* @author rumur
*/
add_action('wp_ajax_fix_taxonomy_count', function() {
$data = (object) $_POST;
try {
if (check_ajax_referer('reindex-post-count')) {
\Rumur\Fix_Taxonomy_Count::make($data->post_type, $data->taxonomy)->process()
? wp_send_json_success(__('Done! Reload the Page?', 'rumur'))
: wp_send_json_error(__('Something went wrong', 'rumur'));
}
} catch (Exception $e) {
wp_send_json_error(__('Something went wrong', 'rumur'));
} catch (Throwable $e) {
wp_send_json_error(__('Something went wrong', 'rumur'));
}
});
<?php
namespace Rumur;
/**
* Class Fix_Taxonomy_Count
* @author rumur
*/
class Fix_Taxonomy_Count
{
/** @var string */
protected $post_type;
/** @var array */
protected $taxonomies;
/** @var string|array */
protected $specific_tax;
/** @var array */
protected $available_tax;
/** @var array */
protected $excluded_tax = [
'nav_menu',
'post_format',
'link_category',
];
/**
* Fix_Taxonomy_Count constructor.
* @param null|string $post_type
* @param string|array $specific_tax
*/
public function __construct($post_type = null, $specific_tax = [])
{
$this->available_tax = get_taxonomies();
$this->setPostType($post_type);
$this->setTaxonomy((array) $specific_tax);
}
/**
* Factory
*
* @return Fix_Taxonomy_Count
*
* @author rumur
*/
public static function make()
{
$self = new self(...func_get_args());
return $self;
}
/**
* @param $post_type
* @return $this
*
* @author rumur
*/
public function setPostType($post_type)
{
if (post_type_exists($post_type)) {
$this->post_type = sanitize_text_field($post_type);
}
return $this;
}
/**
* @param array $taxonomy
* @return $this
*
* @author rumur
*/
public function setTaxonomy(array $taxonomy)
{
// Remove not registered taxonomies
$tax = array_intersect($taxonomy, $this->available_tax);
// Excluded taxonomies are not allowed to process.
$this->taxonomies = array_diff($tax, $this->excluded_tax);
return $this;
}
/**
* @param string| array $tax
*
* @return $this
*
* @author rumur
*/
public function excludeTaxonomy($tax)
{
$tax = (array) $tax;
array_push($this->excluded_tax, ...$tax);
$this->excluded_tax = array_unique($this->excluded_tax);
return $this;
}
/**
* @return bool
*
* @author rumur
*/
public function process()
{
return $this->fixTaxonomyCount();
}
/**
* @return array
*
* @author rumur
*/
protected function getPostTypeTaxonomies()
{
return get_object_taxonomies($this->post_type);
}
/**
* @param array $taxonomy
* @return array
*
* @author rumur
*/
protected function verifyPostTypeTaxonomies(array $taxonomy)
{
return $this->post_type
? array_intersect($this->getPostTypeTaxonomies(), $taxonomy)
: $taxonomy;
}
/**
* @return bool
*
* @author rumur
*/
protected function fixTaxonomyCount()
{
$result = array_map(function ($tax) {
$update_terms = get_terms([
'fields' => 'ids',
'taxonomy' => $tax,
'hide_empty' => false,
]);
return is_wp_error($update_terms)
? false
: wp_update_term_count_now($update_terms, $tax);
}, $this->verifyPostTypeTaxonomies($this->taxonomies));
return !empty(array_filter($result));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment