22

How to Delete Orphaned Post Meta Data in WordPress

Powered by WPCodeBox

This WordPress snippet efficiently deletes orphaned post meta data, ensuring your database remains clean and optimized by removing all metadata not associated with existing posts.


<?php

// Warning! Please create a backup of your database before running this snippet
// This snippet should only be ran in "Manual" mode.

global $wpdb;

$affected_rows = $wpdb->query("DELETE postmeta FROM {$wpdb->postmeta} postmeta LEFT JOIN {$wpdb->posts} posts ON posts.ID = postmeta.post_id WHERE posts.ID IS NULL");

echo "Deleted $affected_rows orphaned meta entries.";

Other Snippets

WPCodeBox is a WordPress Code Snippets Manager that allows you to share your WordPress Code Snippets across your sites.