Skip to content

Instantly share code, notes, and snippets.

@nikola-wd
Last active July 15, 2020 07:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikola-wd/5f5f6c0f8b45457e3c6f4c361ba8f88d to your computer and use it in GitHub Desktop.
Save nikola-wd/5f5f6c0f8b45457e3c6f4c361ba8f88d to your computer and use it in GitHub Desktop.
[clean ACF data] Removes data upon acf field deletion #wordpress #php
// removes ACF data upon field deletion
// this action is run by ACF whenever a field is deleted
// and is called for every field in a field group when a field group is deleted
add_action('acf/delete_field', 'delete_acf_content_on_delete_field');
function delete_acf_content_on_delete_field($field) {
// runs when acf deletes a field
// find all occurences of the field key in all tables and delete them
// and the custom field associated with them
global $wpdb;
// remove any tables from this array that you don't want to check
$tables = array('options', 'postmeta', 'termmeta', 'usermeta', 'commentmeta');
foreach ($tables as $table) {
$key_field = 'meta_key';
$value_field = 'meta_value';
if ($table == 'options') {
$key_field = 'option_name';
$value_field = 'option_value';
}
$table = $wpdb->{$table};
// this query gets all key fields matching the acf key reference field
$query = 'SELECT DISTINCT('.$key_field.')
FROM '.$table.'
WHERE '.$value_field.' = "'.$field['key'].'"';
$results = $wpdb->get_col($query);
if (!count($results)) {
// no content found in this table
continue;
}
// loop through keys and construct list of meta_key/option_names to delete
$keys = array();
foreach ($results as $key) {
$keys[] = $key; // delete acf field key reference
$keys[] = substr($key, 1); // delete acf field value
}
// do escping of all values.... just in case
$keys = $wpdb->_escape($keys);
// delete all of the content
$query = 'DELETE FROM '.$table.'
WHERE '.$key_field.' IN ("'.implode('","', $keys).'")';
$wpdb->query($query);
} // end foreach table
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment