Advertisement
geminilabs

[site-reviews] Fixes term_taxonomy_id values from old WP v4.2 or earlier installations

Dec 28th, 2022 (edited)
2,256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.27 KB | None | 0 0
  1. /**
  2.  * IMPORTANT: Please make a backup of your database that can be restored in case something goes wrong.
  3.  * Do this before using the code snippet!
  4.  *
  5.  * You can use the Code Snippets plugin to run this snippet on your website. Once you have activated the snippet,
  6.  * reload the page and then you can deactivate it and remove it from your website (as this code snippet will run
  7.  * during the page reload).
  8.  *
  9.  * Also, make sure that the Site Reviews plugin is installed.
  10.  *
  11.  * This code snippet does the following:
  12.  *
  13.  * 1. Queries the database for all entries in the wp_term_relationships and wp_term_taxonomy tables.
  14.  * 2. Removes all entries from the wp_term_relationships and wp_term_taxonomy tables.
  15.  * 3. Repopulates the the wp_term_relationships and wp_term_taxonomy tables with the fixed term_taxonomy_id column values.
  16.  *
  17.  * @see: https://salferrarello.com/term_taxonomy_id-vs-term_id/
  18.  */
  19. add_action('plugins_loaded', function () {
  20.     if (!function_exists('glsr')) {
  21.         return;
  22.     }
  23.     if (get_transient('fixed_term_taxonomy_ids')) {
  24.         return;
  25.     }
  26.     global $wpdb;
  27.     $relationships = $wpdb->get_results("SELECT * FROM {$wpdb->term_relationships}", ARRAY_A);
  28.     $termTaxonomys = $wpdb->get_results("SELECT * FROM {$wpdb->term_taxonomy} ORDER BY term_id", ARRAY_A);
  29.     $termIds = wp_list_pluck($termTaxonomys, 'term_id', 'term_taxonomy_id');
  30.     array_walk($relationships, function (&$relationship) use ($termIds) {
  31.         $relationship['term_taxonomy_id'] = $termIds[$relationship['term_taxonomy_id']];
  32.     });
  33.     array_walk($termTaxonomys, function (&$term) {
  34.         $term['term_taxonomy_id'] = $term['term_id'];
  35.     });
  36.     if (!empty($relationships)) {
  37.         $columns = array_keys($relationships[0]);
  38.         $wpdb->query("TRUNCATE TABLE {$wpdb->term_relationships}");
  39.         glsr('Database')->insertBulk($wpdb->term_relationships, $relationships, $columns);
  40.     }
  41.     if (!empty($termTaxonomys)) {
  42.         $columns = array_keys($termTaxonomys[0]);
  43.         $wpdb->query("TRUNCATE TABLE {$wpdb->term_taxonomy}");
  44.         $wpdb->query("ALTER TABLE {$wpdb->term_taxonomy} AUTO_INCREMENT = 0");
  45.         glsr('Database')->insertBulk($wpdb->term_taxonomy, $termTaxonomys, $columns);
  46.     }
  47.     set_transient('fixed_term_taxonomy_ids', true);
  48. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement