Auto Delete Content In Drupal
I have a client that wants to have content posted on his site automatically deleted when it reaches 30 days. His site is built using Drupal and using the hook_cron() will let the scheduled cron job process the node deletions.
I created a Drupal module and in the .module file added function profeng_cron() as the hook and it calls deleteagednodes with the type of content to be removed. The function deleteagednodes does all of the work. I created a query to return all of the nodes that have the desired content types and then using a where clause to filter on the created date. In this example I am setting $expired_time to be now minus 30 days and in the query I am getting records that were created before the $expired_time.
I then take the results from the query and loop through all results. Because the cron job runs as the anonymous user I select the user that owns the node and set the current user to the owner of the node. I then call the Drupal node_delete. When calling node_delete all of the heavy lifting of the delete like writing to the logs and sending notifications are executed.
//cron hook
function profeng_cron()
{
deleteagednodes(’inspectionreport’);
}
//function to delete content by tyoe that is over 30 days old
function deleteagednodes($contenttype)
{
$expired_time = strtotime(’-30 days’);
$query = db_query(”SELECT nid, uid FROM {node} AS n WHERE type = ‘%s’ and created <= ‘%s’”, $contenttype, $expired_time);
while($del = db_fetch_object($query))
{
global $user;
$owner_account = user_load(array(’uid’ => $del->uid));
$temp_user = $user;
$user = $owner_account;
$this_edit['nid'] = $del->nid;
node_delete($this_edit);
$user = $temp_user;
}
}

May 24th, 2009 at 12:20 am
Next time we will be adding the option to delete file attachments as well.
May 26th, 2009 at 10:18 pm
I have update this to now delete the attachments and now have an admin page to set the days until deletion and what content type to delete. It will be posted here soon.