Last active
March 18, 2022 08:44
-
-
Save moritzbappert/58a76611a919511f5cf4610b0601d14e to your computer and use it in GitHub Desktop.
WPML script to remove unnecessary media duplicates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_action('admin_init', function() { | |
global $wpdb, $sitepress; | |
$langs = 3; // set how many languages site has | |
$query = "SELECT ID, post_title, count(ID) AS cnt FROM {$wpdb->prefix}posts WHERE post_type LIKE 'attachment' GROUP BY post_title HAVING cnt > " . $langs; | |
$duplicated = $wpdb->get_results($query); | |
$issues = array(); | |
$i = 0; | |
foreach ($duplicated as $duplicat) { | |
$trid = $sitepress->get_element_trid($duplicat->ID, 'post_attachment'); | |
if (!$trid) { | |
continue; | |
} | |
$translations = $sitepress->get_element_translations($trid, 'post_attachment' ); | |
if (count($translations) < 1) { | |
continue; | |
} | |
foreach ($translations as $lang => $tr) { | |
$issues[$i]['notin'][] = $tr->element_id; | |
} | |
$issues[$i]['post_title'] = $duplicat->post_title; | |
$i++; | |
} | |
foreach ($issues as $issue) { | |
$notin = implode(",", $issue['notin']); | |
$query = "DELETE FROM {$wpdb->prefix}posts WHERE `ID` NOT IN ($notin) AND `post_title` LIKE '" . $issue['post_title'] . "' AND `post_type` LIKE 'attachment'"; | |
$result = $wpdb->query($query); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Make sure to create a database backup before using this. Run this and remove after usage.