Heads up, I'm pretty new to Wordpress... But I need to loop through multiple posts and change all 'data-src' attributes to 'src' so my images will display. What's the way/best way to go about doing this? Would appreciate any info on this topic. Thanks.
2 Answers
You can loop through all your posts and use regex to replace that string. The quick and dirty version would be to just put this in a page template, assign it to a page and then visit said page. If you want something a little cleaner then modify this code to work with something like WP Utility Script Runner.
$posts_to_clean = get_posts(array(
'posts_per_page' => -1,
));
echo 'Posts to clean: ' . count($posts_to_clean) . '<br>';
foreach ($posts_to_clean as $dirty_post) {
$dirty_post->post_content = preg_replace('`(data-src)`', 'src', $dirty_post->post_content);
$updated = wp_update_post($dirty_post, true);
if (!is_wp_error($updated)) {
echo 'Updated post ' . $updated . '<br>';
} else {
echo 'Unable to update post ' . $dirty_post->ID . '<br>';
}
}
echo 'Complete!'
You could also do this directly in your phpmyadmin by a quick search and replace:
Launch phpMyAdmin. Then, you will need to click on your WordPress database name on the left and then click on the SQL tab at the top. Enter this code (be sure to change the table prefix if yours is different)
update wp_posts set post_content =
replace(post_content,'data-src','src');
Then click "go".
And ANOTHER option! Although I don't necessarily like plugins to do this work I know that there is one called Better Search Replace that will do this from within the the dashboard with a simple GUI as well.
data-src
?