Created
May 17, 2022 12:55
-
-
Save koen12344/f264b38631e0706742049316db5e34fc to your computer and use it in GitHub Desktop.
Fetch image from html content
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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