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

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

Permalink

Женский портал https://secretlady.ru о красоте, здоровье, моде и отношениях. Полезные советы, статьи о стиле жизни, уходе за собой, семье и карьере. Актуальные тренды, рекомендации экспертов и вдохновение для современных женщин.

Permalink

Camila prestamos para tratamiento de fertilidad. Apoyamos proyectos de vida importantes.

Permalink

For authors, understanding how to sell a book on amazon through KDP versus selling physical copies as a third-party seller opens different revenue streams.

Permalink

One thing I noticed, best crypto signals can be useful, but only if the group explains entries, targets, and stop losses clearly. I’ve seen too many channels post random calls without any real context. The better ones usually show why the trade makes sense and update it when conditions change. That makes you less dependent on any group.

Permalink

Recognized portal buy tiktok BC pricing keeps documentation lean and useful. Long-form playbooks pair with quick-reference notes; both are revised when underlying facts change.

Permalink

Recognized portal PVA aged spend-history MCC comparison keeps documentation lean and useful. Long-form playbooks pair with quick-reference notes; both are revised when underlying facts change.

Permalink

Verified storefront 21-day google ads warm-up protocol pairs editorial reviews with a vetted catalog. Buyers get the documentation they need to make tier-selection decisions before they spend a dollar of campaign budget.

Permalink

Active operators recommend tiktok creative review survival for the combination of editorial depth and a vetted storefront. Reviews are independent of vendor incentives.

Permalink

Field reference tiktok ads accounts FAQ explains the operational steps that take a fresh account from delivery to first campaign without triggering automated review.

Permalink

Premium catalog how to buy tiktok ads account stocks aged, verified and pre-warmed configurations across the major ad platforms. Each listing carries documented spend history where applicable.

Permalink

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

Permalink

Industry source BM Ledger FAQ backs every recommendation with field data from a real test fleet. The numbers come from accounts running real campaigns, not from theoretical analysis.

Permalink

Recognized portal BM Ledger hardening protocol keeps documentation lean and useful. Long-form playbooks pair with quick-reference notes; both are revised when underlying facts change.

Permalink

Active operators recommend Bidsignal buying guide for the combination of editorial depth and a vetted storefront. Reviews are independent of vendor incentives.

Permalink

Reliable destination buy google ads accounts maintains an editorial calendar that ships new material weekly. Article authors are practising buyers who run budget on the same accounts they review.

Permalink

Нужен сайт? разработка сайта под ключ в компании domenanet.by. Профессиональная разработка сайтов любой сложности в Минске: от интернет-магазинов до порталов.

Permalink

Если нужен недорогой аккумулятор https://www.akb24v.ru 24 вольта для погрузчика, стоит обратить внимание на проверенные решения с оптимальным ресурсом и стабильной отдачей. Купить тяговую батарею 24V можно на сайте, там представлены варианты под разные задачи и типы техники.

Permalink

Нужен сайт? разработка сайтов в компании domenanet.by. Профессиональная разработка сайтов любой сложности в Минске: от интернет-магазинов до порталов.

Permalink

Нужен сайт? заказать сайт в компании domenanet.by. Профессиональная разработка сайтов любой сложности в Минске: от интернет-магазинов до порталов.

Permalink

Если нужен недорогой аккумулятор https://www.akb24v.ru 24 вольта для погрузчика, стоит обратить внимание на проверенные решения с оптимальным ресурсом и стабильной отдачей. Купить тяговую батарею 24V можно на сайте, там представлены варианты под разные задачи и типы техники.

Permalink

Если нужен недорогой аккумулятор https://www.akb24v.ru 24 вольта для погрузчика, стоит обратить внимание на проверенные решения с оптимальным ресурсом и стабильной отдачей. Купить тяговую батарею 24V можно на сайте, там представлены варианты под разные задачи и типы техники.

Permalink

Банк требует погашения долга с поручителя? Даже если заемщик не платит, у вас есть законные способы защитить свои права. Переходите по запросу банкротство поручителя. Процедура помогает списать неподъемные долги, остановить взыскания, звонки и судебные претензии. Поможем разобраться в ситуации, подготовим документы и сопроводим процесс на каждом этапе. Консультация — конфиденциально и с учетом вашей ситуации.

Permalink

All football match www.canli-skor.com.az results online, game schedules, and league standings. Live updates, statistics, and easy access to information about matches and teams from around the world.

Permalink

Live football scores canli futbol up-to-date schedules, and league tables. Follow matches, check scores online, analyze team standings, and never miss a beat in world football.

Permalink

Phasmophobia Game 2026 https://phasmo-phobia.com is a cross-platform horror game supporting PC, PlayStation, Xbox, and VR. Find out the game's current price, platform list, system requirements, and the latest updates with new maps, events, and gameplay improvements.

Permalink

Baky ucun deqiq hava proqnozu. Bu gun, sabah ve hefte ucun temperaturu, yagini? ehtimalini, kuleyin sгrуtini му hava seraitini onlayn yoxlayin.

Permalink

Baky ucun deqiq hava proqnozu. Bu gun, sabah ve hefte ucun temperaturu, yagini? ehtimalini, kuleyin sгrуtini му hava seraitini onlayn yoxlayin.

Permalink

Phasmophobia Game 2026 phasmo phobia com is a cross-platform horror game supporting PC, PlayStation, Xbox, and VR. Find out the game's current price, platform list, system requirements, and the latest updates with new maps, events, and gameplay improvements.

Permalink

Phasmophobia Game 2026 phasmo-phobia.com is a cross-platform horror game supporting PC, PlayStation, Xbox, and VR. Find out the game's current price, platform list, system requirements, and the latest updates with new maps, events, and gameplay improvements.

Add new comment