Programmatically delete a node and redirect user to url

Public

This section creates the endpoint to send the user to. It take one argument and that is a nid. The node is auto loaded into the function even though that is not needed for this example. This hook also makes it mandatory for the user to be logged in.

Get raw version
php
  1. function mymodule_menu() {
  2. $items = array();
  3. $items['api/node/delete/%node'] = array(
  4. 'page callback' => 'api_node_delete',
  5. 'access arguments' => array('access content'),
  6. 'access callback' => 'user_is_logged_in',
  7. 'page arguments' => array(3),
  8. );
  9.  
  10. return $items;
  11. }

This function is fired when the hook_menu is called. You can either use the function directly or activate it by visiting the hook_menu path. There are two arguments, $nid (the node to delete), and $destination (this is there the user will be sent after the node is deleted). If $destination is not set the user will be directed to the home page. There is an option to set/override the $destination var in the function if you user a $_GET['destination'] through a url structure.

Get raw version
php
  1. function api_node_delete($node, $destination = '/') {
  2.  
  3. if(!empty($_GET['destination'])) {
  4. $destination = $_GET['destination'];
  5. }
  6.  
  7. // Set the message including the node title before it is delted.
  8. drupal_set_message($node->nid . ' has been deleted.');
  9.  
  10. // Get the $nid of the node.
  11. $nid = $node->nid;
  12.  
  13. // Delete the node
  14. node_delete($nid);
  15.  
  16. // send the user to the home page or to your custom destination
  17. drupal_goto($destination);
  18. }

Helper function to generate a link to delete the node. Pass it the $nid of the node to be delete.

Get raw version
php
  1. function link_node_delete($nid, $destination = NULL) {
  2. $output = l('Delete', 'api/node/delete/' . $nid, array(
  3. 'query' => array(
  4. 'destination' => $destination,
  5. ),
  6. ));
  7.  
  8. return $output;
  9.  
  10. // using the function this way link_node_delte(1, 'user');
  11. // would return the string <a href="/api/node/delete/1?destination=user">Delete</a>
  12. // the users would click the link and the next think they would see
  13. // is their user account and node/1 would be deleted.
  14. }