WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question

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


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.



share|improve this answer
thanks man , looks like the right way to do it.additional question because i'm really new to wp , where do i run this script? – Kon Mar 18 '13 at 14:45
That will run from pretty much anywhere you put it-- functions.php for example. That isn't a good way to do it since it will run every time a page loads. I tested the code in single.php. It runs when the page reloads. When I do this kind of thing in the real world, I have a kind of shell plugin with a very simple form allowing me to just click a button on the backend. – s_ha_dum Mar 18 '13 at 14:51

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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