I'd like to attach children to a specific Structure entry in a specific order...

  • Entry A
  • Entry B
    • Imported Entry 2
    • Imported Entry 1
    • Imported Entry 3
  • Entry C

I've got a $records array to turn into imported entries:

    'name'      => 'Whatever',
    'updated_at' => '2014-02-27T04:14:29Z',
    'position'   => 1, // int representing the sort order

As I'm looping through my array to create new Craft Structure Entries, I need to be able to define the parent (Entry B), I'm just not sure how. I've figured out how to attach new children to Entry B, I just don't know how to programmatically set their order. My imagination writes code that looks like this:

$parentCriteria = craft()->elements->getCriteria(ElementType::Entry);

$parentCriteria->search  = 'slug:entry-b';
$parentCriteria->section = 'sectionName';
$parentCriteria->type    = 'sectionType';

$entries = $parentCriteria->find();
$parent = $entries[0];

foreach ($records as $row)
    $entry = new EntryModel();

    $entry->sectionId = 4;
    $entry->typeId    = 4;
    $entry->parentId  = $parent->id;
    $entry->authorId  = 1;
    $entry->postDate  = $row->updated_at;
    $entry->title     = $row->name;
    $entry->sortOrder = $row->position; // ← quite impossible!

    $success = craft()->entries->saveEntry($entry);

It's $entry->sortOrder that's completely made up—how do you attach an entry to a specific parent in a specific order?

1 Answer 1


If you're adding them all as new entries anyway, why not just sort the records before you create the entries?

usort($records, array($this, 'sortCategoriesByPosition'));

Add that before your foreach loop, then...

private function sortCategoriesByPosition($a, $b)
    if ($a->position == $b->position)
        return 0; 

    return ($a->position < $b->position) ? -1 : 1;

Stop trying to make things harder than they should be.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.