Search Menu

How to programmatically delete a node from Drupal

How to develop PHP-based web application on Windows machine

Zoo de Granby: a must-visit place on the south shore

Dark Light
One can use the Drupal entityQuery to get all the nodes you want to delete. Then use either the node function delete to delete all versions of a specific node or use the function removeTranslation to delete a specific translated version. In this article I show you how to use them.

Drupal offers the possibility to delete a node via the content page (/admin/content). Where you can delete a particular node or a bulk of nodes, this page is very convenient because you can search for a specific content type and narrow your search by title or other parameters.

Alternatively, you can also delete a node programmatically. Let’s say you need to delete all nodes of a certain type of node. You can first get the list of nodes.

//get nids of a spefici type
$nids = \Drupal::entityQuery('node')
  ->condition('type', 'YOUR-NODE-TYPE')
  ->execute();


//get the list of nodes 
$nodes = \Drupal\node\Entity\Node::loadMultiple($nids);

//you can also use the 
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);

Once you have your list, you can call the delete function from the node or use the entityTypeManager to delete the nodes

//You can use the delete function of the node
foreach($nodes as $node) {
   $node->delete();
}
//You can also use the entityTypeManager
$entityManager = \Drupal::entityTypeManager()->getStorage("node");
foreach($nodes as $node) {
   $entityManager->delete($node);
}

If you have translated nodes, the above code will delete all the versions for a given node. Therefore, if you want to delete only the translation version, you can use the function removeTranslation from a node object.

For example, if the default language of your site is English and you have translated it into French, you can use the code below to delete only the French version

// delete a specific translated version

if ($node->hasTranslation('fr')) {
    $node->getUntranslated()->removeTranslation('fr');
    $node->getUntranslated()->save();
}
Related Posts
Total
0
Share