I have the following temporary filter to fix a content error. We have data in our posts that have 4 digit zip codes, because the leading zero was cut when the original file was created. (For instance, a Massachusetts zip code is 0XXXX, but now in our content it is XXXX)

function fix_zip_code($content){
    if (preg_match('/<span class="postal-code">(\d{4})<\/span>/i',$content, $match)){
        $content = str_replace($match[0],'0'.$match[0],$content);
    return $content;
add_filter('the_content', 'fix_zip_code');

How can I apply that filter to all the content at once and re-save the posts so I can remove the regex filter completely?

2 Answers 2

//run once

$allposts = get_posts('post_status=publish&numberposts=-1');
foreach ($allposts as $thispost) {
     wp_update_post( array(
          'ID' => $thispost->ID,
          'post_content' => fix_zip_code($thispost->post_content)

But as Rarst mentioned, backup your database before doing anything...

  • Oh, duh. Thanks man. I was thinking I'd have to do something and include $wpdb or something way more complex. Might have been more efficient, but this doesn't need to be efficient. It just needs to run once and be done with. Thanks!
    – Dan Gayle
    Commented Nov 3, 2010 at 20:52
  • Well, this is embarrassing. Probably shouldn't have tried that on a blog with 12,000 entries. Runs out of memory :(
    – Dan Gayle
    Commented Nov 3, 2010 at 21:49
  • Ah. haha. Well, maybe you can break the function up into sets and run it once for each set. There's probably a logical way to do something like this, but when I have to run a one-time function like this, I usually put it in my functions.php, hook it to "admin_init" or something else that I can reliably trigger and nobody else is likely to be doing at the same time, then take it out once I've run it. Commented Nov 3, 2010 at 22:51

You can try to approach that from WP/PHP side, but I think in this case it would be easier to run replacement on database.

There are several tools around, for example Search and Replace for WordPress Databases. Just be sure to properly back up database before it and test on separate install if possible.

  • I actually DID fix the same data in the post_meta tables, but mysql's search and replace functionality isn't up to the task, at least according to my company's resident mysql guru. HE said the easiest way would be to do it in WP/PHP :)
    – Dan Gayle
    Commented Nov 3, 2010 at 20:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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