How to properly delete fields, programmatically? I have two content types on my site and I just deleted all the nodes using $node-&gt;delete().

For one of the content types, I noticed that the node body fields did not get deleted, nor did one of the custom fields I made for the content type. All the fields for my other content type were deleted .

So I researched and found the field_purge_field() function. I am not sure how to actually use the function, which is defined as function field_purge_field(FieldConfigInterface $field).
Can someone describe how I would actually load a field and then delete it in this manner (or in a better manner)?

Could I just truncate the tables?
field_purge_field() is described as follows:


  This function assumes all data for the field has already been purged and should only be called by field_purge_batch().


On Drupal, fields are effectively removed during cron tasks; in fact, field_purge_batch() is called from field_cron(), the implementation of hook_cron() done from the Field module. There is no need for you to call neither field_purge_field() nor field_purge_batch().

If you want to write code to purge fields for a node bundle, that code would be similar to the following one. (See the notes after the code, thought.)

  $properties = array(
    'entity_type' =&gt; 'node',
    'bundle' =&gt; 'Your bundle (a.k.a. content type)',
    'include_deleted' =&gt; TRUE,
  );

  $entity_manager = \Drupal::entityTypeManager();

  $fields = $entity_manager-&gt;getStorage('field_config')-&gt;loadByProperties($properties);

  $info = $entity_manager-&gt;getDefinitions();
  foreach ($fields as $field) {
    $entity_type = $field-&gt;getTargetEntityTypeId();

    // Proceed only if the module implementing the entity has not been uninstalled already.
    if (isset($info[$entity_type])) {
      $entity_manager-&gt;getStorage($entity_type)-&gt;purgeFieldData($field, 100);
      field_purge_field($field);
    }
  }


Notes


Purging the fields is thought to be ran during cron tasks; that is why Drupal::entityManager()-&gt;getStorage()-&gt;purgeFieldData() requires the batch size as argument. I used a value of 100, which would possibly allow the code to purge all the fields for that content type, but it could also cause a PHP timeout error. It would be better to run the code from PHP CLI, in order to avoid any execution time out.
You should not need to use this code; in most of the cases, you should execute the cron tasks (which is when Drupal purges the fields of a deleted bundle), or use Drush to purge the fields, either running hook_cron() with it, or executing a specific Drush command (if it exists).


As for truncating the tables, that is the wrong way to proceed. It would not allow Drupal and third-party modules to delete the data they have for the fields; even if you know which tables Drupal uses, you could forget a table used by third-party modules.