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://neotruck.ru компания «НЕО ТРАК» — это современный дилерский центр полного цикла, работающий на рынке коммерческого транспорта и спецтехники уже более 20 лет. Являясь официальным дилером ведущих производителей, таких как DONGFENG, JAC, FAW, DAEWOO TRUCKS, ISUZU, HYUNDAI и других, компания предлагает широкий выбор грузовых автомобилей различной тоннажности, спецтехники, от фургонов и бортовых платформ до эвакуаторов и крано-манипуляторных установок.

Permalink

Практическое руководство по тому, как выбрать тональность контента для целевой аудитории, объясняет механизм построения голоса бренда, который будет восприниматься как естественный и надёжный. Тон коммуникации — это часто недооценённый, но критически важный элемент, влияющий на доверие и лояльность фолловеров. В статье разбираются различные варианты тональности: от профессионально-экспертного до дружелюбно-неформального, от вдохновляющего до прямолинейно-аналитического, и показывается, как каждый из них работает в разных нишах и для разных демографических групп. Материал содержит множество примеров применения тональности на практике: в заголовках, подписях к постам, историях, ответах в комментариях и сообщениях. Для контент-менеджеров, копирайтеров и владельцев бизнесов это станет основой для развития собственного стиля, который будет узнаваем и привлекателен для вашей аудитории.

Permalink

Scaling from modest daily budgets to four-figure spend on Snapchat requires a systematic approach, and how to scale Snapchat Ads without account bans is the cornerstone knowledge every performance marketer needs. The platform's algorithm and policy enforcement have become increasingly sophisticated, making ad account suspension a real risk for campaigns that grow too aggressively or trigger compliance red flags. This guide walks through the exact incremental budget expansion methodology, account structure best practices, and creative rotation tactics that enable sustainable growth without triggering Snapchat's automated monitoring systems. You'll discover the optimal daily increase percentages, frequency cap management, and audience segmentation approaches that separate successful scaling from costly account freezes.

Permalink

Connecting your Facebook assets properly is foundational to scaling ad operations, and how to link Facebook Pages to Business Manager correctly ensures you maintain clean permission hierarchies and avoid costly access conflicts. Many advertisers struggle with permission structures across teams, leading to bottlenecks when scaling campaigns or onboarding new media buyers. This guide walks through the exact steps for linking pages and ad accounts within Business Manager, managing user roles at each asset level, and configuring domain verification to unlock all pixel and conversion tracking features. You'll learn how to assign admin, editor, and analyst permissions to keep your account structure secure while enabling collaboration. Teams managing multiple ad accounts or handling client work will find this especially critical, as proper setup prevents accidental campaign disruptions and maintains audit compliance.

Permalink

Discover how to maintain visual consistency in AI video generation across multiple assets and campaigns without manual frame-by-frame intervention. Media buyers face a persistent challenge: scaling video creative production while preserving brand identity and visual coherence across diverse ad placements. This guide walks through the technical architecture that enables consistent style application, including prompt engineering techniques, model configuration parameters, and post-generation refinement workflows that ensure every frame aligns with your brand guidelines. You'll learn how to leverage seed values, style tokens, and reference imagery to create predictable outputs that maintain aesthetic uniformity across batches of generated content. For teams managing hundreds of video assets monthly, understanding these consistency mechanisms directly reduces approval cycles, minimizes costly re-renders, and accelerates time-to-market for competitive campaigns.

Permalink

Navigating the antidetect landscape in 2026 demands precision because ad platforms continuously evolve their detection systems to identify automation and multi-accounting behavior. This detailed comparison at https://npprteam.shop/en/articles/media-buying/antik-browser-vs-dolphin… walks through the specific technical differences between three market-leading platforms, including fingerprint randomization algorithms, cloud infrastructure vs. local operation trade-offs, and customer support responsiveness during critical account issues. The guide provides benchmarks on account survival rates, detection failure modes, pricing per slot, and integration compatibility with popular media buying tools and automation frameworks. Whether you're scaling from single-account testing to multi-vertical operations or managing client accounts on behalf of agencies, this resource equips you with the comparative data needed to minimize suspension risk while maintaining operational efficiency.

Permalink

Regional audience insights and geo-specific campaign optimization are essential for any TikTok advertiser seeking consistent, profitable scaling. https://npprteam.shop/en/articles/tiktok/how-to-use-geo-targeting-for-a… breaks down the mechanics of selecting target countries, matching account structures to regional demand, and adjusting creative messaging for cultural relevance and engagement. You'll explore real-world examples of how different regions respond to campaign variations, understand the technical setup required for multi-country testing, and learn benchmarks that signal when a geo is ready for budget increase. The content serves media buyers, arbitrage specialists, and affiliate marketers looking to move beyond single-market strategies into diversified, data-driven expansion. Start implementing region-focused tactics today to unlock new revenue streams and reduce dependency on saturated markets.

Permalink

Актуальный обзор лучшие платформы для финансовых кампаний в 2026 сравнивает возможности мейджор-сетей для запуска крипто и финтех офферов без нарушений политик. Финансовый сектор требует прозрачности источников трафика и документального подтверждения легитимности рекламодателя, что отражено в строгих требованиях Google Ads и Meta Ads. Гайд детально разбирает, какие типы аккаунтов Reddit и Twitter позволяют продвигать криптопроекты без ограничений, как структурировать ассоциативные лендинги для обхода автоматических фильтров и какие платежные системы работают с крипто-трафиком. Для агентств, масштабирующих портфель финансовых клиентов, это ресурс для системного подхода к выбору инструментов. Применение рекомендаций сокращает время на согласование с модерацией платформ и повышает стабильность кампаний на 60%.

Permalink

Understanding how to set up Facebook retargeting for small businesses is essential for any operator looking to recover lost sales and maximize limited ad spend. Small business owners often struggle with low conversion rates because they invest heavily in acquiring new visitors but fail to capitalize on warm audiences who have already shown interest. Facebook's retargeting infrastructure allows you to reconnect with site visitors, cart abandoners, and previous customers through pixel-based tracking and custom audiences, creating multiple touchpoints in the buyer journey. The article breaks down practical implementation steps, from installing the Facebook pixel correctly to segmenting audiences based on user behavior and visit depth. Whether you're running a bootstrapped e-commerce store or managing an SMB with modest marketing budget, mastering retargeting fundamentals directly translates to higher ROI and lower cost per acquisition.

Permalink

Стратегия выбора контента TikTok с нуля требует системного подхода, который объединяет анализ рынка, самопознание и практическое тестирование идей на реальной аудитории. Новые авторы часто теряются среди миллионов видео, не понимая, как найти свое место в экосистеме платформы и какие факторы действительно влияют на виральность и рост. Статья предоставляет пошаговый алгоритм изучения топовых каналов в интересующей вас категории, анализ их стратегии постинга, типов контента и взаимодействия с комментариями. Вы получите понимание того, какие ниши наиболее перенасыщены, где есть белые пятна для новых авторов, и как правильно позиционировать себя, чтобы выделиться среди конкурентов. Для медиабайеров и специалистов по цифровому маркетингу эта информация критична для запуска промо-кампаний через микро-инфлюенсеров и оценки качества потенциальных партнеров.

Permalink

Статья о как улучшить CTR в Google Ads предоставляет практическое руководство по увеличению кликабельности объявлений в 2026 году. Многие рекламодатели сталкиваются с проблемой низкого CTR, что напрямую влияет на стоимость конверсии и общую эффективность кампаний. Материал разбирает ключевые факторы, которые определяют привлекательность объявления для пользователей поиска, включая оптимизацию заголовков, формулировку предложений и использование расширений объявлений. Детально описаны проверенные тактики улучшения кликабельности, от выбора более точных ключевых слов до тестирования различных вариантов копирайтинга и структуры объявления. Ресурс предназначен для медиабайеров и маркетологов, которые стремятся снизить затраты на привлечение трафика и максимизировать ROI своих поисковых кампаний. Применение рекомендаций позволит вам добиться значительного прироста кликов при сохранении качества трафика.

Permalink

Implementing a step by step account warmup strategy for media buyers separates professionals who scale sustainably from those who face repeated account lockdowns. Each platform—Facebook's Meta Ads Manager, Google Ads, and TikTok Ads Manager—has distinct trust-building requirements based on how their systems detect and classify risk. The guide covers specific milestones like daily spend progression, audience size thresholds, conversion event verification, and payment method validation that signal legitimacy to platform safety systems. Operators scaling multiple accounts simultaneously benefit from understanding these sequential checkpoints, which prevent common flags like sudden budget jumps, geographic targeting mismatches, or audience overlap patterns. By following a structured warmup timeline, you accelerate your path to full account capacity while maintaining compliance and maximizing early-stage ROAS metrics.

Permalink

Cel mai bun joc Joc wow Un MMORPG legendar cu o lume deschisa vasta, unde te a?teapta batalii epice, progresul personajelor ?i misiuni palpitante. Exploreaza Azeroth, alatura-te breslelor ?i devino parte a unei pove?ti grandioase.

Permalink

Консультацию психолога https://психолог38.рф в Иркутске можно получить в центре Психолог38. Здесь работают высококвалифицированные специалисты: детские психологи, клинические, семейные и индивидуальные. Мы собрали профессионалов разных направлений, чтобы комплексно подходить к решению запросов клиентов. Бережно, деликатно, с научным подходом. Сложные ситуации в нашей жизни встречаются не редко, и своевременная помощь, поддержка очень важна. Находясь среди людей, легко можно оказаться в одиночестве, один на один со своими проблемами. Если вы ищите лучших психологов, которые реально помогают людям, обратите внимание на нашу организацию.

Permalink

Консультацию психолога https://психолог38.рф в Иркутске можно получить в центре Психолог38. Здесь работают высококвалифицированные специалисты: детские психологи, клинические, семейные и индивидуальные. Мы собрали профессионалов разных направлений, чтобы комплексно подходить к решению запросов клиентов. Бережно, деликатно, с научным подходом. Сложные ситуации в нашей жизни встречаются не редко, и своевременная помощь, поддержка очень важна. Находясь среди людей, легко можно оказаться в одиночестве, один на один со своими проблемами. Если вы ищите лучших психологов, которые реально помогают людям, обратите внимание на нашу организацию.

Permalink

Консультацию психолога https://психолог38.рф в Иркутске можно получить в центре Психолог38. Здесь работают высококвалифицированные специалисты: детские психологи, клинические, семейные и индивидуальные. Мы собрали профессионалов разных направлений, чтобы комплексно подходить к решению запросов клиентов. Бережно, деликатно, с научным подходом. Сложные ситуации в нашей жизни встречаются не редко, и своевременная помощь, поддержка очень важна. Находясь среди людей, легко можно оказаться в одиночестве, один на один со своими проблемами. Если вы ищите лучших психологов, которые реально помогают людям, обратите внимание на нашу организацию.

Permalink

Нужна градирня? https://gradirni.mystrikingly.com ключевой элемент системы охлаждения, позволяющий эффективно снижать температуру воды за счет теплообмена с воздухом. Применяется в промышленности, энергетике и на предприятиях. Обеспечивает стабильную и экономичную работу оборудования.

Permalink

Нужна градирня? https://gradirni.mystrikingly.com ключевой элемент системы охлаждения, позволяющий эффективно снижать температуру воды за счет теплообмена с воздухом. Применяется в промышленности, энергетике и на предприятиях. Обеспечивает стабильную и экономичную работу оборудования.

Permalink

Нужна септик или погреб? https://septikidlyadoma.mystrikingly.com эффективное решение для автономной канализации. Системы обеспечивают качественную очистку сточных вод, устраняют запахи и безопасны для окружающей среды. Подходят для частных домов, коттеджей и загородных участков.

Permalink

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

Permalink

Сайт для женщин https://prowoman.kyiv.ua практичные советы по уходу за собой, здоровью и отношениям. Читайте, развивайтесь и улучшайте свою жизнь.

Permalink

Строительный портал https://solution-ltd.com.ua с актуальной информацией и практическими решениями. Узнайте о новых технологиях, сравните материалы, получите советы и найдите специалистов. Сделайте ремонт или строительство проще, быстрее и выгоднее.

Permalink

Сайт для женщин https://prowoman.kyiv.ua практичные советы по уходу за собой, здоровью и отношениям. Читайте, развивайтесь и улучшайте свою жизнь.

Permalink

Все о здоровье https://mikstur.com на одном портале: болезни, симптомы, методы лечения и профилактика. Советы врачей, актуальные медицинские статьи и рекомендации. Помогаем лучше понимать организм и заботиться о своем самочувствии.

Permalink

Женский сайт https://fashionadvice.kyiv.ua полезная информация о здоровье, стиле, любви и карьере. Читайте актуальные статьи и находите решения для жизни.

Permalink

Онлайн строительный https://reklama-region.com журнал для профессионалов и частных застройщиков. Полезные статьи, разборы материалов, новинки рынка и практические рекомендации. Все о строительстве, ремонте и дизайне в удобном формате.

Permalink

Сайт для женщин https://bestwoman.kyiv.ua статьи о красоте, здоровье, отношениях и стиле жизни. Полезные советы, тренды и идеи для вдохновения. Все, что нужно современной женщине, в одном месте.

Permalink

Строительный журнал https://tozak.org.ua с полезными статьями и актуальными обзорами. Освещаем современные технологии, материалы и тренды в строительстве и ремонте. Практические советы, идеи и решения для создания комфортного и надежного пространства.

Permalink

Женский онлайн портал https://stepandstep.com.ua все о жизни, стиле и здоровье. Статьи о красоте, отношениях, семье и саморазвитии. Полезный контент для женщин любого возраста.

Permalink

Женский онлайн портал https://stepandstep.com.ua все о жизни, стиле и здоровье. Статьи о красоте, отношениях, семье и саморазвитии. Полезный контент для женщин любого возраста.

Permalink

Туристический портал https://swiss-watches.com.ua для путешественников: направления, маршруты, советы и лайфхаки. Подбор отелей, билетов и экскурсий, идеи для отдыха и полезные рекомендации. Планируйте поездки легко и открывайте новые страны с комфортом.

Permalink

Онлайн курсы рабочих https://obuchenie-rabochih.ru профессий — это быстрый старт в новой карьере. Практика, поддержка наставников и современные методики помогут вам освоить специальность и найти работу.

Permalink

Нужно масло или смазка? масло редукторное clp 320 краснодар официальный дилер масел Devon и смазок Efele в Краснодаре предлагает широкий ассортимент продукции для промышленности и автосервиса. Гарантия качества, выгодные цены, быстрая доставка и профессиональная консультация по подбору.

Permalink

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

Permalink

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

Permalink

ParfumPlus https://parfumplus.ru это сервис доставки оригинальных духов по всей России. Мы помогаем удобно и безопасно заказать любимые ароматы, не рискуя столкнуться с подделками. В нашем каталоге представлен широчайший выбор женских и мужских духов, туалетной воды, нишевая и люксовая парфюмерия, популярные бестселлеры и новинки мировых брендов.

Permalink

Продажа стройматериалов https://mir-betona.od.ua в Одессе по доступным ценам. В наличии всё необходимое для ремонта и строительства: от базовых материалов до профессионального инструмента. Быстрая доставка и гарантия качества.

Add new comment