Forum

Thread tagged as: Question, Blog

Exporting Blog Posts into a collection

Is there a way to export a list of blog posts from a particular category i.e all the blog posts that have a category of recipe and import them them into a collection, so it is separate from the blog, without having to do it manually.

Any help with this would be great.

Cheers

Fishtank Creative

Fishtank Creative 2 points

  • 5 years ago
Drew McLellan

Drew McLellan 2638 points
Perch Support

There's no direct feature for that, but it's certainly possible.

Unsupported and needs you to customise it, but here's a rough import script:

<?php
    include('../perch/runtime.php');

    $API = new PerchAPI(1, 'dm_import');

    $posts = perch_blog_custom([
            'skip-template' => true,
        ]);

    $collectionID = 3;

    $Collections = new PerchContent_Collections;
    $Items       = new PerchContent_CollectionItems;

    $Collection  = $Collections->find($collectionID);
    $Collection->set_current_user(1);
    $options     = $Collection->get_options();

    $Template    = new PerchTemplate('content/'.$Collection->collectionTemplate(), 'content');
    $tags        = $Template->find_all_tags_and_repeaters('content');
    $Form        = new PerchForm('edit');

    $Resources = new PerchResources;

    if ($posts) {
        foreach($posts as $post) {

            $CollectionItem = $Collection->add_new_item();
            $subprefix = '';
            $id = $CollectionItem->itemID();

            $form_vars      = [];
            $file_paths     = [];
            $search_text    = ' ';
            $form_vars['_id'] = $id;

            // map the fields
            $new_item = [
                'postTitle'           => $post['postTitle'],
                'postDescHTML'        => $post['postDescHTML'],
            ];

            $postitems = $new_item;

            list($form_vars, $search_text) = PerchContent_Util::read_items_from_post($CollectionItem, $tags, $subprefix, $form_vars, $postitems, $Form, $search_text, $options, $Resources, false, $Template);

            if (isset($form_vars['_blocks'])) {
                $form_vars['_blocks'] = PerchUtil::array_sort($form_vars['_blocks'], '_block_index');
            }

            $data = [];
            $data['itemJSON']   = PerchUtil::json_safe_encode($form_vars);
            $data['itemSearch'] = $search_text;

            $CollectionItem->update($data);
            $Collection->sort_items($CollectionItem->itemID());
            $CollectionItem->publish();
            $CollectionItem->index();
            echo 'Imported: '.$post['postTitle'].'<br>';
        }
        $Collection->clean_up_resources();
    }

    PerchUtil::output_debug();

Thanks for this. Ill have a go.