Sometimes we like to post tech tips. This a web development tip for people into Drupal.  Hopefully it’ll help somebody somewhere out there!

——

If you deal with tons of nodes and want to clean up old, unused, unpublished nodes after a while, here’s one way to do it. I did it via coding in my own Drupal module. However you could also use the Auto Expire module. The problem I had with this is that I couldn’t find a way to actually delete the nodes.

[Note: This was for Drupal 5. It may still work in newer versions but I haven’t tested or researched it.]

I started with a menu item in hook_menu. The code below lets you access the script via a page at /delete:

$items[‘delete’] = array(
‘title’ => t(‘Delete Vehicles’),
‘page callback’ => ‘delete_old_nodes’,
‘access arguments’ => array(‘access_content’),
‘type’ => MENU_CALLBACK,
);

Then make a function to do the deletion.

function delete_old_nodes() {

Now get the node id’s and the time that each node was last updated.

$result = db_query(“SELECT nid, changed FROM {node} WHERE node.type = ‘auto’”);

Then we loop through each result. In this loop we check the date last updated versus today’s date. Drupal stores dates as UNIX timestamps, that is, the seconds since the UNIX epoch. Don’t let that confuse you – it’s merely the number of seconds since a date in 1970. It’s just a handy way to have a universally standard numeric date value.

while($node = db_fetch_object($result)) {
$i=0;

Here we get a UNIX timestamp of right now:

$today = date(‘U’);

Then we calculate the difference of seconds between when the node was last updated and now:

$difference = $today – $node->changed;

A day is 86,400 seconds. So we divide our $difference seconds by that to get the number of days since the node was last modified:

$days = $difference / 86400;

In my case, I wanted to delete nodes after 10 days so I did it thusly:

if($days > 10) {
node_delete($node->nid);
$i++;
}

You might be wondering about that little $i variable. It’s a simple counter to show how many were deleted. So you can end your delete function with this:

echo(“$i autos <b>deleted</b>.<br />”);

Below is the full, unbroken code. Hopefully this helps somebody!

function delete_old_nodes() {
$result = db_query(“SELECT nid, changed FROM {node} WHERE node.type = ‘auto’”);
$i=0;

while($node = db_fetch_object($result)) {
$today = date(‘U’);

$difference = $today – $node->changed;
$days = $difference / 86400;
if($days > 10) {
node_delete($node->nid);
$i++;
}
}
echo(“$i autos <b>deleted</b>.<br />”);
}

Comments

comments

Loading...