This is a re-do of a post I made a couple of years ago. The code in that post is outdated and won’t work as expected, so I wanted to provide working code to replace that. Also, with the GDPR regulations, many site managers will want to give users an automatic way to delete their data from the database. In this tutorial, I’ll give you a way to do that.
First Step: Create the Delete Switch
Whether the record is deleted automatically or not, you’ll need the delete switch. I suggest you set this up by defining a new field (maybe call it “Delete Record” as I’ve done in the example) that is a checkbox field with “yes” in the values parameter of the field.
You can maybe put something in the help text that explains that the data will be gone permanently, and they shouldn’t click the box unless they really mean it.
Should You Let Your Users Delete Their Own Records?
The main problem with letting users delete their own record is they may do it unintentionally, and there isn’t any way to recover a deleted record once it’s done. I mean, it wouldn’t be deleted if this was possible, right? So, what I recommend for most sites is a “Delete My Record” switch that doesn’t actually delete the record, but only hides it temporarily until it is deleted by an administrator.
If you want your delete switch to simply hide the record, you need to build that into your lists using a list shortcode filter, for example:
Hiding the “deleted” record from single record displays and frontend record edit displays is a bit more complex, you need to use a custom template to prevent such records from showing.
We’re Going to Let Them Do It: Here’s How
I created a simple plugin that you can install that will give your users the ability to actually delete a record. This will be irreversible, so make sure your users understand this.
First, of course, you need to set up the delete switch as described above. Then, download and install the plugin below. If you used the same field name for your delete switch as I used above, you won’t need to edit the plugin. There is a message that is shown to the user when they delete their record (line 72), you may want to edit that.
If your delete switch field has a different name, you should change the value of the $delete_switch_field_name property on line 15.
The plugin also fires an event when the record is deleted. The main use for that is to trigger an email to the admin and/or the user to notify them of the deletion. This requires the Email Expansion Kit add-on. If you are a coder, you can use the event for other things you may want to do when this happens.