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.


// 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.

Copyright © 2021 WPCodeBox SRL. All other trademarks are the property of their respective owners
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram