Ajax - Create tag with custom ID programatically I'm trying to create an jQuery/Ajax script to import data from a Wordpress API service and want to import the WP tags into my database.

Everything works as expected when I loop through the data and send it to /actions/tags/createTag but I'd like to keep the original tag IDs in order to be able to import the posts later and keep the relationship with their tags (Craft automatically assigns a length+1 ID to new tags).

Any way I can do this?
You'll need to create a new table/record to store the data

class IdRecord extends BaseRecord
{
    /**
     * Returns the name of the database table the model is associated with (sans table prefix). By convention,
     * tables created by plugins should be prefixed with the plugin name and an underscore.
     *
     * @return string
     */
    public function getTableName()
    {
        return 'ids';
    }

    /**
     * Returns an array of attributes which map back to columns in the database table.
     *
     * @access protected
     * @return array
     */
    protected function defineAttributes()
    {
        return array(
            'oldId'   =&gt; AttributeType::Number,
            'newId' =&gt; AttributeType::Number
        );
    }
}


Create a new Controller and store with the record

public function actionCreateTag()
{
    $this-&gt;requireLogin();
    $this-&gt;requireAjaxRequest();

    $tag = new TagModel();
    $tag-&gt;groupId = craft()-&gt;request-&gt;getRequiredPost('groupId');
    $tag-&gt;getContent()-&gt;title = trim(craft()-&gt;request-&gt;getRequiredPost('title'));
    $oldId = craft()-&gt;request-&gt;getRequiredPost('oldId');

    if (craft()-&gt;tags-&gt;saveTag($tag))
    {

        $tagMap = new IdRecord();
        $tagMap-&gt;oldId = $oldId;
        $tagMap-&gt;newId =  $tag-&gt;id;
        $tagMap-&gt;save();
        $this-&gt;returnJson(array(
            'success' =&gt; true,
            'id'      =&gt; $tag-&gt;id
        ));
    }
    else
    {
        $this-&gt;returnJson(array(
            'success' =&gt; false
        ));
    }
}


And when you are saving your entries you'll do

$entry = new EntryModel();
// ... set your content
$oldId = 'number of your old WP tag id';
$tag = IdRecord::model()-&gt;find('oldId = :oldId',[
    'oldId' =&gt; $oldId
]);
$entry-&gt;getContent()-&gt;setAttribute('yourTagFieldHandle', $tag-&gt;newId);


You can use pluginfactory.io to create your boilerplate.

Edit

Another approach. If you receive the title of the tags as an array like ['tag1', 'tag2', 'tag3'] would be something like

$ids = [];
foreach($tagTitles as $tagTitle){
    $criteria = craft()-&gt;elements-&gt;getCriteria(ElementType::Tag);
    $criteria-&gt;title = 'your Tag Title';
    $tag = $criteria-&gt;first();
    if($tag){
        $ids[] = $tag-&gt;id;
    }
}
$entry-&gt;getContent()-&gt;setAttribute('yourFieldHandle', $ids);