0

I have a bunch of regular expressions that I want to run on my posts to update the post_content field, when a series of conditions are met, some of them require a combination of various values from ACF. Long story short I need a way to be able to programmatically edit the content of all my posts using preg_replace

I've been learning about the wp_insert_post_data filter, and it works, but it only works for the current post that is being edited. Is there any way to do this in WordPress where I can loop through all posts and update the content similarly?

Here's what I currently have.

add_filter('wp_insert_post_data', 'mystuff', 99, 2);
function mystuff($data, $post)
{
    $content = $data['post_content'];
    $regex = '/MYCRAZYREGEXSTUFF/';
    $match = preg_match($regex, $content, $matches);
    if ($match) {
        $updatedContent = preg_replace($regex, '', $content);
        $data['post_content'] = $updatedContent;
    }
    return $data;
}
2
  • You can do regex search replace on your whole database with wp-cli.
    – Rup
    Commented Dec 4, 2020 at 13:48
  • So since I need to be able to query fields to use in my regex replacement value, I can't use a plain DB regex routine.
    – Joe Seifi
    Commented Dec 5, 2020 at 20:55

1 Answer 1

0

I ended up just writing a function inside of my template's index.php like this.

function fancySearchAndReplace() {
    $regex = '/myregex/';
    $my_posts = get_posts(array('post_type' => 'post', 'numberposts' => -1));
    foreach ($my_posts as $post) {
        $content = $post->post_content;
        $theID = $post->ID;
        $thing = get_field('thing', $theID);
        $updatedContent = preg_replace($regex, $thing, $content);
        wp_update_post(array(
            'ID' => $theID,
            'post_content' => $updatedContent,
        ));
    }
}

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.