Delete orphaned post meta from the WordPress Database

Back to Blog

The post meta table holds information related to WordPress posts. Oftentimes, as you delete posts, or other plugins delete posts, and don’t clean the meta. The post meta table can have a lot of useless data in it. That data doesn’t belong to any post, and it’s just taking up space on your servers.

In my experience, I saw sites that had over 13 million entries in the post meta table, this can cause a huge load on the database and on your server.

This code snippet can be run using the manual option in WPCodeBox, so you can run it only when you think it’s necessary. It will search for all the post meta for which the post id doesn’t exist anymore and deletes it.

It’s a good practice to take a complete backup system in place, and take a backup of your database before using any code that performs modifications on the database.

When you run code snippets manually in WPCodeBox, you will be presented with an output. This snippet will output the number of orphaned meta entries it found and deleted.

<?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.";

This code snippet is available on the WPCodeBox WordPress Snippet repository, and accessible from within the plugin.

The Most Powerful Code Snippets Plugin

Save hours when customizing WordPress sites.
Manage Snippets in WordPress
Works with All Plugins
Send Snippets to the Cloud
A Better Code Editor
Conditionally Run Snippets
Works Locally, or In the Cloud

Get WPCodeBox, the most powerful WordPress Code Snippet Manager.

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