Esportare i dati da WordPress a MongoDB

Esportare i dati da WordPress a MongoDB

Esportare i dati da WordPress a MongoDB è relativamente semplice.

Creiamo il database in MongoDB:

use myblog;

Con la nostra prima collezione:

db.createCollection('posts');

Quindi creiamo uno schema per i nostri post:

{
  "title": String,
  "date": Date,
  "content": String,
  "excerpt": String,
  "slug": String,
  "thumb": String,
  "category": Array,
  "tag": Array
}

Abbiamo in pratica creato una corrispondenza con la struttura di base dei post di WordPress.

Ora creiamo una pagina nascosta in WordPress con un template specifico nel nostro tema. Se avete molti post vi consiglio di usare posts_per_page e offset nel Loop.

<?php /* Template Name: Export */
get_header();
?>

<?php
    $export_file = 'posts.json';
    $loop = new WP_Query( array( 'post_type' => 'post', 'posts_per_page' => -1 ) );
    $data = array();
    while( $loop->have_posts() ):
       $loop->the_post();
       $id = get_the_ID();
       $upload_dir = wp_upload_dir();
       $base_upload_url = $upload_dir['baseurl'] . '/';
       $thumb = wp_get_attachment_image_src( get_post_thumbnail_id( $id ), 'full' );
       $image = str_replace( $base_upload_url, '/uploads/', $thumb[0] );
       $cats = get_the_category( $id );
       $tags = get_the_tags();

       $categories = array();
       $post_tags = array();

       if ( !empty( $cats ) ) {
           foreach( $cats as $cat ) {
              $categories[] = array(
                  'name' => $cat->name,
                  'slug' => $cat->slug,
                  'description' => $cat->description
              );
           }
       }

       if( $tags ) {
          foreach( $tags as $tag ) {
                      $post_tags[] = array(
                          'name' => $tag->name,
                          'slug' => $tag->slug,
                          'description' => $tag->description
                      );    
          }
       }

       $datum = array();

       $datum['title'] = get_the_title();
       $datum['date'] =  get_the_date( 'Y-m-d g:i:s', $id );
       $datum['content'] = get_the_content();
       $datum['excerpt'] = strip_tags( get_the_excerpt() );
       $datum['slug'] =  basename( get_permalink( $id ) );
       $datum['thumb'] = $image;
       $datum['category'] = $categories;
       $datum['tag'] = $post_tags;

       $data[] = $datum;

    endwhile;
    wp_reset_postdata();

    $json = json_encode( $data );
    file_put_contents( TEMPLATEPATH . '/' . $export_file, $json );
?>
<?php get_footer(); ?>

Ora avete un file JSON nella directory del vostro tema e potete importare i post in MongoDB:

mongoimport -d myblog -c posts --file posts.json --jsonArray

Bisogna correggere le date dei post:

use myblog;
db.posts.find().forEach(function(post){
  post.date = ISODate(post.date);
  db.posts.save(post);
});    

La procedura è identica per le pagine e i custom post type, ma in generale è consigliabile creare collezioni separate.

Per gli allegati ad esempio possiamo creare questa collezione:

db.createCollection('media');

Con la seguente struttura di base per i documenti:

{
  "date": Date,
  "type": String,
  "url": String
}

Quindi modifichiamo il nostro template come segue:

$export_file = 'media.json';
$attachments = get_posts( array(
        'post_type' => 'attachment',
        'posts_per_page' => -1,
        'post_status' => 'any', 
        'post_parent' => null 
    ) );
    $data = array();

    if( $attachments ) {
        foreach( $attachments as $attachment ) {
            setup_postdata( $attachment );
            $id = get_the_ID();
            $upload_dir = wp_upload_dir();
       $base_upload_url = $upload_dir['baseurl'] . '/';
       $att_url = wp_get_attachment_url( $id );           $url = str_replace( $base_upload_url, '/uploads/', $att_url );
            $datum = array();
            $datum['date'] = get_the_date( 'Y-m-d g:i:s', $id ); 
            $datum['type'] = $attachment->post_mime_type;
            $datum['url'] = $url;

            $data[] = $datum;
        }
        wp_reset_postdata();
        $json = json_encode( $data );
    file_put_contents( TEMPLATEPATH . '/' . $export_file, $json );
    }

Importiamo i dati:

mongoimport -d myblog -c media --file media.json --jsonArray

Correggiamo nuovamente le date:

use myblog;
db.media.find().forEach(function(m){
  m.date = ISODate(m.date);
  db.media.save(m);
});    

Come si può notare, non c’è nulla di realmente difficile in questa procedura.

Torna su