Extract image src from a post and send it to an external form

There is no built-in way to extract an image/image-src from the post body. If the images are attachments you can do it with get_children or WP_Query, and wp_get_attachment_image_src.

function get_image_src_from_content_101578($content) {
  global $post;
  $args = array( 
    'post_parent' => $post->ID,
  );
  $images = get_children($args);
  foreach ($images as $img) {
    var_dump(wp_get_attachment_image_src($img->ID));
  }
}
add_action('the_content','get_image_src_from_content_101578');

You could also use regex.

function replace_image_link_101578($content) {
  $pattern = '|<img.*?src="https://wordpress.stackexchange.com/questions/101578/([^"]*)".*?/?>|';
  $content = preg_match($pattern,$content,$matches);
  var_dump($matches);
  return $content;
}
add_filter('the_content','replace_image_link_101578');

The latter might be less work for the server, but may also be less reliable. If you have images embedded that aren’t attachments, it will be your only choice though.

A non-hook example that returns only the image src attribute, if found.

function replace_image_link_($content) {
  $pattern = '|<img.*?src="https://wordpress.stackexchange.com/questions/101578/([^"]*)".*?/?>|';
  $content = preg_match($pattern,$content,$matches);
  return (!empty($matches[1])) ? $matches[1] : '';
}

Leave a Comment