Skip to content

Instantly share code, notes, and snippets.

@koen12344
Created May 17, 2022 12:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koen12344/f264b38631e0706742049316db5e34fc to your computer and use it in GitHub Desktop.
Save koen12344/f264b38631e0706742049316db5e34fc to your computer and use it in GitHub Desktop.
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