Skip to content

WordPress regex search and replace without plugin

WordPress regex search and replace without plugin

Plugins sometimes are unnecessarily bloated and heavy, causing lots of load on the server. Hence, inserting source codes manually is sometimes the better option.

Warning: make a backup of your data before you proceed

In the theme editor, go to your functions.php file and add the following code to the bottom of the file. The scenario below is that I had a bunch of <iframe> tags where I forgot to add the attribute 'allowfullscreen' and I would rather avoid using a filter for 'the_content' as it will cause unnecessarily load. Your use case will most likely be different, so feel free to adapt the code so that it works for you.

If you need to test your regex, you can do so usingĀ regex101

add_action('init','update_post_content');

function update_post_content()
{
    $my_posts = get_posts( array('post_type' => 'post') ); // Modify the post type - post, page etc

    foreach ( $my_posts as $my_post ):
        $post_content = $my_post->post_content;
        if( strstr($post_content, 'allowfullscreen') ) // if the allowfullscreen attribute exist already, then skip
            continue;
    
        $updated_post_content = preg_replace("/^(iframe).+?(?=><)/", "$0 allowfullscreen", $post_content); 
    	$my_post->post_content = $updated_post_content;

    	wp_update_post( $my_post );

    endforeach;
}

After you have successfully modified whatever you want to modify, remember to remove the code (unless you intentionally wish to keep it)

 

Enjoyed the content ? Share it with your friends !
Published inDevelopmentProgramming

Be First to Comment

Leave a Reply

Your email address will not be published.