Get first URL from custom field, download and set as featured image on post publish

I have a plugin that is adding text and a URL to a custom field when the post is published (not saved as draft). I want to get/make a function or plugin to search within the custom field and sideload the image from a URL, then add that image as the featured image.

Doing some searching I found this function from another StackExchange post that was designed to get a thumbnail from a Youtube video:

    function set_youtube_as_featured_image($post_id) {  

    // only want to do this if the post has no thumbnail
    if(!has_post_thumbnail($post_id)) { 

        // find the youtube url
        $post_array = get_post($post_id, ARRAY_A);
        $content = $post_array['post_content'];
        $youtube_id = get_youtube_id($content);

        // build the thumbnail string
        $youtube_thumb_url = 'http://img.youtube.com/vi/' . $youtube_id . '/0.jpg';

        // next, download the URL of the youtube image
        media_sideload_image($youtube_thumb_url, $post_id, 'Sample youtube image.');

        // find the most recent attachment for the given post
        $attachments = get_posts(
            array(
                'post_type' => 'attachment',
                'numberposts' => 1,
                'order' => 'ASC',
                'post_parent' => $post_id
            )
        );
        $attachment = $attachments[0];

        // and set it as the post thumbnail
        set_post_thumbnail( $post_id, $attachment->ID );

    } // end if

} // set_youtube_as_featured_image
add_action('save_post', 'set_youtube_as_featured_image');

function get_youtube_id($content) {

    // find the youtube-based URL in the post
    $urls = array();
    preg_match_all('#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#', $content, $urls);
    $youtube_url = $urls[0][0];

    // next, locate the youtube video id
    $youtube_id = '';
    if(strlen(trim($youtube_url)) > 0) {
        parse_str( parse_url( $youtube_url, PHP_URL_QUERY ) );
        $youtube_id = $v;
    } // end if

    return $youtube_id; 

} // end get_youtube_id

The only thing missing here is the ability to search a custom field and pull the URL from there, although the function certainly is in the right direction with finding the URL. Can anyone give me some direction here? The text is formatted in the custom field as below. It is the only URL and has an img html tag with it.

<div class="newsread " style="margin-bottom: 20px;">
                        <div id="ncbubuhome">
                                    <p>Erdenet Mining Corp. is the Mongolian and Russian joint venture to hold copper and molybdenum mining and production of copper and molybdenum concentrates and is counted as one of the biggest manufactures in Asian region. The corporation held its annual report last Friday in Erdenet city.</p>

<p>We are delivering the numbers of Erdenet Mining Corp. in comparison with Oyu Tolgoi LLC. Although those entities have differences in their operation period and investment agreement, those two are considered as biggest projects for Mongolia.</p>                                     <p><img alt="" src="http://gstat.mn/newsn/images/ck/2015/03/31/Erdenet_Oyutolgoi_Eng-171337-1287730770.jpeg" style="height:3572px; width:825px"></p>                        </div>

I've been bashing my head against this and have tried a few things:

  • Copying content of custom field to post body then using a plugin to autoset the external image (I believe things were being instantiated out of order and I couldn't get it to work)
  • Putting a shortcode in the body of the article with a placeholder that would pull a custom field, but couldn't figure out how to get the placeholder to work in the text editor.

Any help is much appreciated! I've been trying this for three days now! -Robert

Solutions

You can access custom fields like that:

 get_post_meta($post_id, $key, $single);

see https://codex.wordpress.org/Custom_Fields

you could extent some of the plugins that already solve the rest of your problem like the wp-autoset-featured-image-plus plugin and tell it to use the string from your custom field instead of the post body.

the relevant code part should be this line in the function wpasfip_post_thumbnail_html:

preg_match_all( '/<img .*?(?=src)src=\"([^\"]+)\"/si', strtolower($post->post_content), $allpics );

i guess if you just replace $post->post_content whith the string from your custom field it should work.

Similar questions

How to automatically hit download URL and download a file using javascript?
In WordPress there's a feature that exports your data into xml files. You can hit this URL with parameters and it will start downloading XML file. The cat parameter indicates the ID of the category containing posts you want to include in the XML file. The problem is that I have over 200 categories and I want to export every category into separate f...
PHP/Wordpress: Capture OnClick Event 'Download URL; and Pass it To 'Thank You' Page for Initializing Download
In wordpress, I have a single.php page that features a download link to a file using an onclick event. This is what my href looks like today: I basically want a user to click on the DOWNLOAD link, then go to a 'Thank You' page where the file would begin downloading. But also, to grab the TITLE of that page and pass that too. I envision the flow as ...
WP dynamic featured image - Can't get second featured image url
I'm actually working on a wordpress website with a Dessign.net theme (the pixel one) which got a beautiful full-page slider on the front page. The slider shows the featured image of selected posts (post for which i've checked "show in slideshow" in the meta box field on edit page). Those featured image are used in the same way for different view on...
How can I get the featured image or the first image for a post/page and display it as a banner?
I'm making a travel site and for each page/post I want to display a google map and an image of the place referenced in the post/page the image is kind of banner-size so I dont think that the post thumbnail would do (unless I can get the high-res image of which the thumbnail comes from) I thought of getting the first image of the post and wrap it in...
Set first image (external) as featured image / thumbnail
I've read through a lot of code snippets now and it seems like wether I'm to stupid or there is no solution for this. I have a setup where some information for a product is loaded via amazon API if I enter the ASIN code in a meta box when creating a post. When I save the post, the Amazon product image is automatically shown in the post. But it isn'...
"Use as featured image" not working , "Set Featured Image" hangs. GoDaddy Issue
What my site runs on: What happens when i click use as featured image ? What I tried The problem was on 3.4.1 so i updated it to 3.4.2 ( Issue not resolved ) Changed the theme to the basic twenty ten ( Issue not resolved ) Wordpress support forums seem to sway towards the fact that its a wordpress core code issue and not an issue with the themes.

Also ask

We use cookies to deliver the best possible experience on our website. By continuing to use this site, accepting or closing this box, you consent to our use of cookies. To learn more, visit our privacy policy .