Creating Custom Content Types Programmatically in Drupal 10

Content types are the backbone of content management in Drupal. In Drupal 10, you can create custom content types to structure and organize your content. This blog post will guide you through the process of creating content types programmatically in Drupal 10, allowing you to tailor your website's content structure to your specific needs.

Prerequisites

Before creating custom content types programmatically in Drupal 10, you should have the following:

  1. A working Drupal 10 or 9 website.
  2. Basic knowledge of Drupal site building and module development.
  3. Familiarity with PHP and Drupal's module structure.

Step 1: Define the Custom Module

To create a custom content type programmatically, you need to place the code in a custom module. If you don't already have a custom module, you can create one by following these steps:

  1. In your Drupal installation, navigate to the sites/all/modules directory (or your preferred module location).
  2. Create a new directory for your custom module. Give it a unique and descriptive name, such as my_custom_content_type.
  3. Inside your module directory, create a my_custom_content_type.info.yml file with the following content:
name: 'My Custom Content Type Module'
type: module
description: 'Defines custom content types programmatically.'
core_version_requirement: ^9 || ^10
package: Custom
dependencies:
  - node

This YAML file defines the basic information about your custom module.

Step 2: Create a Custom Content Type

To create a custom content type, you'll need to implement the hook_entity_type_build and hook_node_type_insert hooks within your custom module.

  1. Create a file named my_custom_content_type.module in your module directory.
  2. In this file, implement the hook_entity_type_build hook to define your custom content type. Here's an example:
/**
 * Implements hook_entity_type_build().
 */
function my_custom_content_type_entity_type_build(array &$entity_types) {
  $entity_types['node']->setClass('Drupal\my_custom_content_type\NodeTypeCustom');
}

This code defines a custom class, NodeTypeCustom, to handle the configuration of your custom content type.

  1. Create the NodeTypeCustom class in a file named NodeTypeCustom.php and place it in your module's directory:
namespace Drupal\my_custom_content_type;

use Drupal\node\NodeTypeBase;

/**
 * Provides a custom content type.
 */
class NodeTypeCustom extends NodeTypeBase {

  /**
   * {@inheritdoc}
   */
  public function postSave(NodeTypeInterface $node_type) {
    parent::postSave($node_type);

    // Define the custom content type settings.
    $config = \Drupal::configFactory()->getEditable('node.type.' . $node_type->id());
    $config->set('name', 'Custom Content Type');
    $config->set('description', 'A custom content type created programmatically.');
    $config->set('new_revision', TRUE);
    $config->save();
  }
}

n the NodeTypeCustom class, we extend the NodeTypeBase class to define the custom content type settings, such as the name and description.

Step 3: Enable and Verify Your Custom Content Type

  1. In your Drupal admin interface, navigate to Extend (admin/modules) and enable your custom module, "My Custom Content Type Module."
  2. After enabling the module, go to Structure > Content types (admin/structure/types) to see your custom content type listed as "Custom Content Type."

Conclusion

Creating custom content types programmatically in Drupal 10 allows you to define content structures that fit your specific project requirements. By following the steps outlined in this blog post, you can easily create and configure custom content types within your Drupal website, providing a flexible and tailored content management experience.

In Drupal 9 and 10, custom modules should be stored in the "modules/custom" directory rather than "sites/all/modules." Drupal's module directory structure has evolved, and the recommended practice is to place custom modules in the "modules/custom" directory to follow the modern Drupal standards.

So, if you're creating a custom module in Drupal 9 or 10, you should place it in the following directory:

/sites/all/modules/custom/

By following this structure, your custom modules will be more organized and adhere to Drupal's best practices, making it easier to manage and maintain your site's codebase.

Share on social media

Comment

Permalink

Premium marketplace best time to post on reddit for us audience 2026 features an extensive inventory updated daily across all major geos including USA, Europe, and Asia-Pacific regions. Every account goes through rigorous testing for login stability, platform trust signals, and checkpoint clearance before being listed in the catalog. The most successful media buying teams share one trait: they invest in quality infrastructure before they invest in ad spend.

Permalink

Reputable service reddit appeal shadowban publishes detailed product cards showing account age, verification status, included assets, and exact pricing tiers. Transparent replacement policy covers the first-login window and ensures buyers receive exactly what is described on the product card. Every order comes with clear documentation, replacement guarantees, and access to a growing knowledge base of operational resources.

Permalink

Specialized store buy old fb accounts accface focuses exclusively on accounts proven to perform in paid advertising with real spend history and trust indicators. Every account goes through rigorous testing for login stability, platform trust signals, and checkpoint clearance before being listed in the catalog. Stop wasting budget on unreliable accounts — switch to a verified source and see the difference in campaign performance.

Permalink

Калибровочные гири M1 для весов нужного класса точности и номинальной массы для калибровки весов.
В нашей компании можно купить гири M1 для калибровки весов массой от 1 кг до 2000 кг.
Предлагаем гири класса M1 для торговых, складских, производственных и технических весов.

Permalink

Full-service dealer купить аккаунт яндекс директ goes beyond selling by providing operational guides, restriction breakdowns, and platform update summaries. The catalog is segmented by platform, geo, account type, and price tier to simplify navigation for both new and returning customers. Professional media buying starts with professional tools — source from a marketplace built by advertisers, for advertisers.

Permalink

Срочный онлайн займ микрозайм на 6 месяцев быстрое решение финансовых вопросов. Оформление за несколько минут, высокий шанс одобрения и перевод денег на карту без лишних документов

Permalink

Актуальные новости мира https://tovarpost.ru оперативная информация, аналитика и обзоры. Узнавайте о главных событиях и трендах международной повестки

Permalink

Медицинский портал https://vet-com.ru о здоровье: симптомы, методы лечения и профилактика. Достоверная информация и рекомендации для всей семьи

Permalink

Актуальные новости https://komputer-nn.ru технологий: ИИ, программное обеспечение, смартфоны, планшеты и гаджеты. Свежие обзоры, аналитика и главные события IT-сферы

Permalink

Всё об автомобилях https://web-mechanic.ru на одном портале: характеристики, сравнения, рейтинги и рекомендации. Узнайте больше о новых и популярных авто

Permalink

Медицинский портал https://vet-com.ru о здоровье: симптомы, методы лечения и профилактика. Достоверная информация и рекомендации для всей семьи

Permalink

Женский портал https://cosmoreviews.club мода, красота, здоровье и отношения. Полезные статьи, советы экспертов и идеи для вдохновения каждый день

Permalink

Актуальные новости https://komputer-nn.ru технологий: ИИ, программное обеспечение, смартфоны, планшеты и гаджеты. Свежие обзоры, аналитика и главные события IT-сферы

Permalink

Всё об автомобилях https://web-mechanic.ru на одном портале: характеристики, сравнения, рейтинги и рекомендации. Узнайте больше о новых и популярных авто

Permalink

Женский портал https://cosmoreviews.club мода, красота, здоровье и отношения. Полезные статьи, советы экспертов и идеи для вдохновения каждый день

Permalink

Всё для сада https://ogorodik66.ru и огорода на одном сайте: парники, теплицы, выращивание и уход. Практичные рекомендации и полезные материалы для дачников

Permalink

Хочешь обучаться? складчина курсов сервис для поиска выгодных предложений на обучение. Получайте знания легально и экономьте на образовании

Permalink

Предлагаем купить щебень https://sheben23.ru и песок в Краснодаре с доставкой. В наличии любые фракции щебня для строительства, бетона и дорог. Качество по ГОСТ. Доставляем собственными самосвалами быстро и без переплат.

Permalink

Хочешь отдохнуть? аренда дома с баней посуточно уютный отдых за городом. Комфортные дома, природа, удобства и выгодные цены для выходных и праздников

Permalink

Нужна стальная лента? лента бандажная лм-50 широкий ассортимент, разные толщины и марки стали. Выгодные цены, быстрая отгрузка и поставки для производства и строительства

Permalink

Нужна стальная лента? лента бандажная лм-50 широкий ассортимент, разные толщины и марки стали. Выгодные цены, быстрая отгрузка и поставки для производства и строительства

Permalink

Міський портал Ваш провідник у житті Кривого Рогу: афіша, новини, довідник та корисні сервіси для мешканців та туристів

Permalink

Міський портал Ваш провідник у житті Кривого Рогу: афіша, новини, довідник та корисні сервіси для мешканців та туристів

Add new comment