File: /var/www/innodrive/migrations/relation-fix.php
<?php
$postRu = (int)$argv[1];
$postEn = (int)$argv[2];
//define('APPLICATION_ENV', 'development');
define( 'SHORTINIT', true );
require( './public/wp-load.php' );
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
$currentRelations = $wpdb->get_results('SELECT wtt.* FROM wp_term_relationships wtr
JOIN wp_term_taxonomy wtt on wtr.term_taxonomy_id = wtt.term_taxonomy_id
WHERE wtr.object_id IN (' . $postRu . ', ' . $postEn .') AND wtt.taxonomy = "post_translations"');
echo 'Current relations:' . PHP_EOL;
print_r($currentRelations);
if (count($currentRelations)) {
echo 'removing old relations' . PHP_EOL;
foreach($currentRelations as $relation) {
$wpdb->delete('wp_term_relationships', [
'term_taxonomy_id' => $relation->term_taxonomy_id
]);
$wpdb->delete('wp_term_taxonomy', [
'term_taxonomy_id' => $relation->term_taxonomy_id
]);
$wpdb->delete('wp_terms', [
'term_id' => $relation->term_id
]);
}
}
echo 'Creating new Relations' . PHP_EOL;
$description = serialize(['ru' => $postRu, 'en' => $postEn]);
$name = 'pll_' . generateRandomString(13);
$wpdb->insert('wp_terms', [
'name' => $name,
'slug' => $name,
'term_group' => 0
]);
$termId = $wpdb->insert_id;
$wpdb->insert('wp_term_taxonomy', [
'term_id' => $termId,
'taxonomy' => 'post_translations',
'description' => $description,
'parent' => 9,
'count' => 2
]);
$termTaxonomyId = $wpdb->insert_id;
$wpdb->insert('wp_term_relationships', [
'object_id' => $postRu,
'term_taxonomy_id' => $termTaxonomyId,
'term_order' => 0
]);
$wpdb->insert('wp_term_relationships', [
'object_id' => $postEn,
'term_taxonomy_id' => $termTaxonomyId,
'term_order' => 0
]);
echo 'THE END' . PHP_EOL;