Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Fetch image from html content
<?php
function pgmb_insert_content_img($localPost, $post_id, $is_autopost, $location){
if(
!class_exists('DOMDocument') ||
!class_exists('\PGMB\Google\MediaItem')
){ return $localPost; }
$form_fields = get_post_meta($post_id, 'mbp_form_fields', true);
if(!isset($form_fields['mbp_content_image']) || !empty($form_fields['mbp_post_attachment'])){
return $localPost;
}
$parent_post_id = wp_get_post_parent_id($post_id);
$parent_post = get_post($parent_post_id);
$doc = new DOMDocument();
@$doc->loadHTML($parent_post->post_content);
$tags = $doc->getElementsByTagName('img');
if(empty($tags)){ return $localPost; }
foreach($tags as $tag){
$first_image_src = $tag->getAttribute('src');
break;
}
if(!isset($first_image_src)){ return $localPost; }
$mediaItem = new \PGMB\Google\MediaItem('PHOTO', $first_image_src);
$localPost->addMediaItem($mediaItem);
return $localPost;
}
add_filter('mbp_create_post', 'pgmb_insert_content_img', 10, 4);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment