Migrating old posts to new wp, how to extrapolate infos from the post body to custom fields?

I need to migrate some information that are store in the post body (like “price:200$”), extrapolate them somehow and put them into custom fields. how do I do that?

The blog is about restaurants and the location and prices are written in the body of the posts, I need to have them into custom fields so I can perform searches on them.

Related posts

Leave a Reply

1 comment

  1. The short answer is that you Loop over all of you posts and use (probably) preg_match to extract information.

    The long answer is that this could be pretty tricky, depending on how consistent your data entry is. Here is an example:

    global $wpdb;
    $sql = "SELECT ID,post_content FROM {$wpdb->posts}";
    $allp = $wpdb->get_results($sql);
    foreach ($allp as $p) {
      // Deal with price
      $pat = '/price:[0-9]+$/';
      $price = preg_match($pat,$p->post_content,$matches);
      if (!empty($matches[0])) {
        list($key,$value) = explode(':',$matches[0]);
        update_post_meta($p->ID, $key, $value, $value);
        $new_content = preg_replace($pat,'',$p->post_content);
        //     var_dump($new_content);
      }
      // end of price
    
      // update content if needed
      if (!empty($new_content)) {
        $post = array(
          'ID' => $p->ID,
          'post_content' => $new_content
        );
        wp_update_post($post);
      }
    
    }
    

    That will convert the “price” data you listed above– price:200$– and put it into a meta field (*_postmeta) under the key “price” with a value of “200$”. I’d recommend not including the $ in the value so you can sort numerically if you ever want to. There are a number o questions here asking how to sort alphanumeric data numerically, and you can’t. You need to solve that as the data goes into the database.

    You will need a similar regex for each of the bits of information you want to pull out of post_content.

    Be very careful. It is easy to get the regex wrong, and there is no ‘undo’. Work on a development server with a copied, and disposable, database until you know you have things right.

    Reference:

    http://php.net/manual/en/function.preg-match.php
    http://www.php.net/manual/en/function.preg-replace.php
    http://codex.wordpress.org/Function_Reference/update_post_meta
    http://codex.wordpress.org/Function_Reference/wp_update_post