0

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.

3
  • so you have raw html in the post content that contains data-src?
    – mrben522
    Commented Mar 19, 2019 at 16:18
  • That's right. I have over 500 different posts and most contain images. Although the only way I could bulk upload the data (CSV) was using an importer that converted my data to posts although the plugin would remove the src tag, therefor my way around it was to change 'src' to 'data-src' and change it back after the data was uploaded. <img data-alt="" data-src="/cms/photo/newsheadlines/Dec_3.jpg" style="width: 100%;" /> Commented Mar 19, 2019 at 16:22
  • 1
    I'd add to any answer the usual warnings about database backups before making changes like that. I'd test on a backup copy to make sure that your syntax doesn't affect other things by mistake. If you don't want to change the actual content, some client-side JS against the content could be done at page display time. Although that wouldn't affect anyone that is not allowing client-side JS. Commented Mar 19, 2019 at 18:53

2 Answers 2

0

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!'
0

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.

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.