Best practice way to delete user meta data during plugin uninstall?

If a plugin stores data in the usermeta tables what is the best practice method to delete these entries for all users in uninstall.php? I could access the database directly but is there another way?

4 s
4

You should not access the database directly, if at all possible. There are two main reasons for this:

  • If the database structure changes (unlikely), your queries may become outdated. Using functions like delete_user_meta() will ensure that your query should work properly for all WordPress versions (past, present, and future) that support that function.

  • Caching. If you don’t clean up the cache after deleting your data, it could cause problems. If you delete your data manually, you also need to clean up the cache manually. Using built in functions that do this automatically is definitely a better idea.

For deleting meta data (such as user meta fields), I would recommend using the delete_metadata() function. This function has a fifth parameter that you can set to true to remove the metadata with a given meta_key for all objects (in this case users). Example:

$meta_type="user";
$user_id    = 0; // This will be ignored, since we are deleting for all users.
$meta_key   = 'your_meta_key';
$meta_value=""; // Also ignored. The meta will be deleted regardless of value.
$delete_all = true;

delete_metadata( $meta_type, $user_id, $meta_key, $meta_value, $delete_all );

You can repeat that for each meta key your plugin uses.

Leave a Comment