Skip to content

Instantly share code, notes, and snippets.

@moritzbappert
Last active March 18, 2022 08:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moritzbappert/58a76611a919511f5cf4610b0601d14e to your computer and use it in GitHub Desktop.
Save moritzbappert/58a76611a919511f5cf4610b0601d14e to your computer and use it in GitHub Desktop.
WPML script to remove unnecessary media duplicates
<?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);
}
});
@moritzbappert
Copy link
Author

Make sure to create a database backup before using this. Run this and remove after usage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment