Skip to content

Instantly share code, notes, and snippets.

@wpjess
Created June 12, 2020 22:26
Show Gist options
  • Save wpjess/2b7fca863eb40b2e122187c80c3cc03a to your computer and use it in GitHub Desktop.
Save wpjess/2b7fca863eb40b2e122187c80c3cc03a to your computer and use it in GitHub Desktop.
Recalculate WordPress term counts
<?php
require 'wp-load.php';
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = $mysqli->query("SELECT term_taxonomy_id FROM ".$table_prefix."term_taxonomy")){
while ($row = mysqli_fetch_array($result)) {
$term_taxonomy_id = $row['term_taxonomy_id'];
echo "term_taxonomy_id: ".$term_taxonomy_id." count = ";
$countresult = $mysqli->query("SELECT count(*) FROM ".$table_prefix."term_relationships WHERE term_taxonomy_id = '$term_taxonomy_id'");
$countarray = mysqli_fetch_array($countresult);
$count = $countarray[0];
echo $count."<br />";
$mysqli->query("UPDATE ".$table_prefix."term_taxonomy SET count = '$count' WHERE term_taxonomy_id = '$term_taxonomy_id' AND post_status = 'publish'");
}
}
if ($result = $mysqli->query("SELECT ID FROM ".$table_prefix."posts")){
while ($row = mysqli_fetch_array($result)) {
$post_id = $row['ID'];
echo "post_id: ".$post_id." count = ";
$countresult = $mysqli->query("SELECT count(*) FROM ".$table_prefix."comments WHERE comment_post_ID = '$post_id' AND comment_approved = 1");
$countarray = mysqli_fetch_array($countresult);
$count = $countarray[0];
echo $count."<br />";
$mysqli->query("UPDATE ".$table_prefix."posts SET comment_count = '$count' WHERE ID = '$post_id'");
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment