Skip to content

Instantly share code, notes, and snippets.

@patrickfreitasdev
Created February 22, 2024 04:10
Show Gist options
  • Save patrickfreitasdev/bfe47889c06394d4ad504eb7fc949200 to your computer and use it in GitHub Desktop.
Save patrickfreitasdev/bfe47889c06394d4ad504eb7fc949200 to your computer and use it in GitHub Desktop.
<?php
add_action('admin_init', 'fix_duplicated_post_meta');
function fix_duplicated_post_meta()
{
if (!isset($_GET['fix-divi-duplicated-post-meta'])) return;
$post_meta = '_et_pb_use_builder';
// select posts with duplicated post meta
global $wpdb;
$query = "SELECT post_id, meta_key, meta_value, COUNT(*) c
FROM $wpdb->postmeta
WHERE meta_key = '$post_meta'
GROUP BY post_id, meta_key, meta_value
HAVING c > 1";
$posts = $wpdb->get_results($query);
// loop through posts and delete duplicated post meta
foreach ($posts as $post) {
$post_id = $post->post_id;
$query = "SELECT * FROM $wpdb->postmeta WHERE post_id = $post_id AND meta_key = '$post_meta'";
$postmetas = $wpdb->get_results($query);
$postmeta_ids = array_map(function ($postmeta) {
return $postmeta->meta_id;
}, $postmetas);
$postmeta_ids = array_slice($postmeta_ids, 1);
$postmeta_ids = implode(',', $postmeta_ids);
$query = "DELETE FROM $wpdb->postmeta WHERE meta_id IN ($postmeta_ids)";
$wpdb->query($query);
}
//flush object cache
wp_cache_flush();
//admin alert message
add_action('admin_notices', 'fix_duplicated_post_meta_notice');
function fix_duplicated_post_meta_notice()
{
?>
<div class="notice notice-success is-dismissible">
<p><?php _e('Duplicated post meta has been fixed, please remove the code.', 'sample-text-domain'); ?></p>
</div>
<?php
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment