home
Hero image for: How to get a list of content types in Drupal 8

How to get a list of content types in Drupal 8

By Eduardo García ● CTO | December 3rd, 2015

Continuing with the series of articles about how to do Drupal development everyday tasks using Drupal 8 way I will share today how you could get a list of content types available programmatically.

Using the following code, you could print the complete list

$contentTypes = \Drupal::service('entity.manager')->
    getStorage('node_type')->loadMultiple();

$contentTypesList = [];
foreach ($contentTypes as $contentType) {
    $contentTypesList[$contentType->id()] = $contentType->label();
}

print_r($contentTypesList);

After executing the code above, you will output similar to the following snippet:

Array
(
    [article] => Article
    [page] => Basic page
)

Of course in my example, I want a list of values machine-name -> human label, but you can manipulate the Drupal\node\Entity\NodeType entity to do advanced things.

I hope you found this article useful.