Use the code LIFETIME at checkout and get 20% off our limited-time lifetime plans.

Delete orphaned post meta from the WordPress Database

WordPress Code Snippets
 / Delete orphaned post meta from the WordPress Database

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.

WPCodeBox
Complete WordPress Code Snippets Manager with Cloud Support
Copyright © 2021 WPCodeBox SRL
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram