<p>Adding to Paul Verheul's excellent answer (and to answer question by Floriskoch) — to test for the existence of a category before creating it, you might try something like the following (untested).</p>

<pre><code>// Get category group from known id
$categoryGroup = craft()-&gt;categories-&gt;getGroupById(2);

// Find categories matching group and title
$criteria = craft()-&gt;elements-&gt;getCriteria(ElementType::Category);
$criteria-&gt;group = $categoryGroup;
$criteria-&gt;title = "My Category Title";
$criteria-&gt;limit = null;
$categories = craft()-&gt;elements-&gt;findElements($criteria);

// 1 or more matching categories exist; select first category
if($categories) {
    $categoryId = $categories[0]-&gt;id; // only want first category if more than one with the same title

// no categories exist; create category
} else {
    $category = new CategoryModel();
    $category-&gt;groupId = 2;
    $category-&gt;getContent()-&gt;title = 'My new category title';
    if(craft()-&gt;categories-&gt;saveCategory($category)) {
        $categoryId = $category-&gt;id;
    }
}

// double check we have a category id
if($categoryId) {
    $entryModel = new EntryModel();
    $entryModel-&gt;title = 'My entry's title';
    $entryModel-&gt;myCategoryFieldHandle[] = $categoryId;

    if(craft()-&gt;entries-&gt;saveEntry($entryModel)) {
        ...
    }
}
</code></pre>

CC BY-SA 3.0
2016-12-04T14:16:42.910Z
2016-12-04T14:16:42.910Z
Douglas McDonald
<p>To create a category, you'd have to use the <a href="http://buildwithcraft.com/classreference/services/CategoriesService#saveCategory-detail" rel="nofollow"><code>craft()-&gt;categories-&gt;saveCategory()</code></a> method, and feed it a CategoryModel. Having done that, you can use the ID of your new category to create an array for the entry's category field (in this example its handle is <code>categoryFieldHandle</code>):</p>

<pre><code>$category = new CategoryModel();
$category-&gt;groupId = 2; // Or whatever ID your new category's group has.
$category-&gt;getContent()-&gt;title = 'My new category title'; // Slug will be automagically created

if(craft()-&gt;categories-&gt;saveCategory($category)) {
    $entryModel = new EntryModel();
    $entryModel-&gt;title = 'My entry's title';
    $entryModel-&gt;categoryFieldHandle[] = $category-&gt;id;

    if(craft()-&gt;entries-&gt;saveEntry($entryModel)) {
        ...
    }
}
</code></pre>

CC BY-SA 3.0
2015-01-26T18:15:05.410Z
Assuming that more than one entry will have the same category, you might also need to add a conditional to check whether the category already exists.
Douglas McDonald
CC BY-SA 3.0
2015-01-27T01:29:33.910Z
+1 to what @DouglasMcDonald said - I'm working through that right now.
Adam McCombs
CC BY-SA 3.0
2016-11-21T16:53:32.473Z
@DouglasMcDonald, how would I do that? Is there a specific utility method for that purpose? Thanks!
Floriskoch
CC BY-SA 3.0
2016-12-04T13:21:28.513Z
@Floriskoch No special utility methods. You would just need to test for the existence of the category using the groupId and category title. I would probably use an `ElementCriteriaModel` for this.
Douglas McDonald
CC BY-SA 3.0
2015-01-26T09:06:26.710Z
2015-01-27T03:33:52.573Z
2015-01-27T03:33:52.573Z
Paul
<p>We're working on an XML import plugin to migrate content from another CMS.</p>

<p>What's the best way to create a new category (with a name, slug etc.) and assign it to the entry when running 
<code>$entryModel = new EntryModel();</code> ?</p>

<plugin-development><categories><import>
Best way to programmatically create categories?
# Best way to programmatically create categories?

(Asked by: username_0 on 2015-01-26)

We're working on an XML import plugin to migrate content from another CMS.

What's the best way to create a new category (with a name, slug etc.) and assign it to the entry when running
`$entryModel = new EntryModel();` ?

**Tags:** plugin-development, categories, import


---

## 2 answers

### Answer by username_2 on 2015-01-26. Score: 6 | Accepted answer

To create a category, you'd have to use the craft()->categories->saveCategory() method, and feed it a CategoryModel. Having done that, you can use the ID of your new category to create an array for the entry's category field (in this example its handle is categoryFieldHandle):
$category = new CategoryModel();
$category->groupId = 2; // Or whatever ID your new category's group has.
$category->getContent()->title = 'My new category title'; // Slug will be automagically created

if(craft()->categories->saveCategory($category)) {
    $entryModel = new EntryModel();
    $entryModel->title = 'My entry's title';
    $entryModel->categoryFieldHandle[] = $category->id;

    if(craft()->entries->saveEntry($entryModel)) {
        ...
    }
}

> **Comments:**
> **username_1**: Assuming that more than one entry will have the same category, you might also need to add a conditional to check whether the category already exists.  
> **username_0**: +1 to what @DouglasMcDonald said - I'm working through that right now.  
> **username_3**: @DouglasMcDonald, how would I do that? Is there a specific utility method for that purpose? Thanks!  
> **username_1**: @username_3 No special utility methods. You would just need to test for the existence of the category using the groupId and category title. I would probably use an `ElementCriteriaModel` for this.  

---

### Answer by username_1 on 2016-12-04. Score: 2

Adding to username_2 Verheul's excellent answer (and to answer question by username_3) — to test for the existence of a category before creating it, you might try something like the following (untested).
// Get category group from known id
$categoryGroup = craft()->categories->getGroupById(2);

// Find categories matching group and title
$criteria = craft()->elements->getCriteria(ElementType::Category);
$criteria->group = $categoryGroup;
$criteria->title = "My Category Title";
$criteria->limit = null;
$categories = craft()->elements->findElements($criteria);

// 1 or more matching categories exist; select first category
if($categories) {
    $categoryId = $categories[0]->id; // only want first category if more than one with the same title

// no categories exist; create category
} else {
    $category = new CategoryModel();
    $category->groupId = 2;
    $category->getContent()->title = 'My new category title';
    if(craft()->categories->saveCategory($category)) {
        $categoryId = $category->id;
    }
}

// double check we have a category id
if($categoryId) {
    $entryModel = new EntryModel();
    $entryModel->title = 'My entry's title';
    $entryModel->myCategoryFieldHandle[] = $categoryId;

    if(craft()->entries->saveEntry($entryModel)) {
        ...
    }
}


---

