How to programmatically create nodes, comments and taxonomies in Drupal 7
I've been busy with a migration work for my client recently. There is an established website built with some proprietary CMS with a decent amount of articles / pages, different categories and user comments. My team was hired to make a complete migration from this money-sucking old-fashioned proprietary CMS to a modern shiny open-source Drupal 7. I like this kind of tasks. It’s always a pleasure to help people get rid of an old and proprietary technologies.
To accomplish this task, I needed to create nodes, comments and taxonomies programmatically in Drupal 7, which is a pretty trivial task for Drupal 6. But in D7 with the introduction of entities and fields in core (aka CCK in core) things have changed a bit. In today's post I'll show you how to programmatically create nodes, comments and taxonomies in Drupal 7.
In detail you’ll find out how to:
1. Programmatically create a node:
- Initialize a node object
- Add body field
- Add custom fields
- Add file / image field
- Add a term to a node
- Save a node
2. Programmatically create a comment
3. Programmatically create a term
1. How to programmatically create a node
1.1 Initialize a node object
1 2 3 4 5 6 7
*We set LANGUAGE_NONE for $node->language, if you don’t have the locale module enabled, the node will not be assigned any particular language. So that's why we put here the constant LANGUAGE_NONE. In Drupal, nodes and fields can exist in more that one language, so if your site is multilingual you should specify the language code for your field. You can configure languages and get language codes by going this path in Drupal administration: Configuration -> Regional and language -> Languages.
1.2 Add a body field
1 2 3 4
1.3 Add custom fields
1 2 3 4 5
1.4 Add file / image fields
1 2 3 4 5 6 7 8 9 10
1.5 Add a term to a node
field_tags here is the name of a term reference field attached to your content type, 1 is a term id you wish to assign to a node. Simple!
1.6 Save a node
2. How to programmatically create a comment
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
3. How to programmatically create a taxonomy term
This one is the most easiest part of the tutorial. To create a term you just need to do the following:
1 2 3 4 5
Well, that’s all for today my friends, hope this article helps you. Please leave your comments and additions and if you liked the post, share it on twitter and facebook, spread the knowledge!