1

I already added a featured post image to all my posts (>1000). Some posts (around 700) still have an image at the beginning of the post content.

Now I need to remove all images which are right at the beginning of the post content. I need to leave the images untouched which are not at the beginning.

Because of that I can't just remove "the first image tag occurrence in the post" because then I would remove images from the post content.

Maybe this plugin here Permanently remove first image from posts could be used as a base but what would be re regex or query to reflect this requirements?

1
  • You could check the first html tag from every post content with DomDocument and process your script only if it's an image or a link wrapping an image.
    – Luis Sanz
    Commented Jul 21, 2016 at 16:44

1 Answer 1

2

Suppose you haven't modified anything to change the default content output, maybe this can help:

add_filter('the_content', function($content)
{
  $content = preg_replace('~^<p><img([^>]+)></p>~i', '', $content, 1);

  return $content;
}, PHP_INT_MAX);
4
  • The problem with this is that if the first image is repeated elsewhere in the post, all instances will be removed.
    – jgraup
    Commented Jul 22, 2016 at 3:08
  • @jgraup Ah, haven't thought about that ;-). I have just updated the answer.
    – Minh Tri
    Commented Jul 22, 2016 at 3:40
  • Hi! Thank you! I added this remove line breaks, white space and non-breaking space only at the start of the post. Maybe you can add that to your answer? $clean = preg_replace("/^<img[^>]+\>/i", "", $post->post_content, 1); $cleaner = preg_replace('/^\s+/', ' ',$clean); $moreclean = ltrim($cleaner); $cleanest = str_replace("^&nbsp;", "", $moreclean); $pid = wp_update_post(array( 'ID' => $post->ID, 'post_content' => $cleanest ));
    – Marc
    Commented Jul 22, 2016 at 10:54
  • @Marc Hey! I don't quite understand what you're doing but feel free to add your own answer and mark it as a true answer if it's more correct for you. But remember to vote for helpful answers as well. ;-)
    – Minh Tri
    Commented Jul 22, 2016 at 11:06

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.