WordPress.org

Ready to get started?Download WordPress

Forums

Function to set the featured image/thumbnail? (16 posts)

  1. ChimpanzeeUK
    Member
    Posted 3 years ago #

    I'm trying to write a bit of PHP to loop through all my posts and create a thumbnail from a URL containing one of my custom fields.

    Most of my posts include a YouTube video and every such post also has a custom field: youtube_id. I can grab the video thumbnail using the Google API with the following URL: http://img.youtube.com/vi/youtube_id/0.jpg. I then want to import the image and set it as the post's featured image.

    What I was thinking/hoping is that I'd be able to write a script to loop through all of my posts and do something like:

    $thumb_url = 'http://img.youtube.com/vi/' . get_post_meta($post->ID, 'youtube_id', true) . '/0.jpg';
    set_post_thumbnail($thumb_url);

    My theoretical code would use this imagined function, 'set_post_thumbnail', which unfortunately doesn't seem to exist! :) But I'm very new to this sort of thing so my code probably wouldn't work at all anyway, even if the function did exist!

    Can anyone suggest a way to achieve what I'm after (assuming you can make sense of it)? The alternative would be to make a change to my theme to just display the image straight from the URL but I'd rather actually import it so that WordPress crops and resizes it appropriately.

    Thanks in advance for your help.

  2. alchymyth
    Forum Moderator
    Posted 3 years ago #

  3. ChimpanzeeUK
    Member
    Posted 3 years ago #

    Thanks alchymyth.

    I was going to do that but I thought that method isn't used anymore. It's probably my misunderstanding. Are thumbnails the same as featured images? Sorry, I'm returning to WordPress after not having used it for a while and the new thing seems to be 'Featured images'. Do these replace thumbnails or are they the same thing, stored in the same way, but with a different name?

  4. Rev. Voodoo
    Volunteer Moderator
    Posted 3 years ago #

    You got it, same thing, different name

  5. Justin Sternberg
    Member
    Posted 3 years ago #

    Wow ChimpanzeeUK, you are trying to do the exact thing i was looking to do today. Did you ever figure out a way to do the theoretical "set_post_thumbnail($thumb_url)"?
    BTW the set_post_thumbnail function does exist now, but it requires an id. http://codex.wordpress.org/Function_Reference/set_post_thumbnail

  6. ChimpanzeeUK
    Member
    Posted 3 years ago #

    Hi Justin

    No, I'm afraid I never got this working. I just generate the thumbnail manually every time. If you figure out a way, please post back. :)

  7. Justin Sternberg
    Member
    Posted 3 years ago #

    I did get... it will still need some conditional code when you save it, or else it will just add a new image to the post every time you save it, but this seems to work well. This code will also extract the youtube id from the youtube url.

    // Save Featured Image If It's a youtube video
    add_action('save_post', 'wds_video_sideload_post_thumb');
    function wds_video_sideload_post_thumb() {
    global $post;
    
        $youtube_url = get_post_meta( $post->ID, 'videobox', true );
        $youtubeid = youtubeid($youtube_url);
            $thumb_url = 'http://img.youtube.com/vi/'. $youtubeid .'/0.jpg';
    
            require_once(ABSPATH . 'wp-admin/includes/file.php');
            require_once(ABSPATH . 'wp-admin/includes/media.php');
            set_time_limit(300);
    
            if ( ! empty($thumb_url) ) {
                // Download file to temp location
                $tmp = download_url( $thumb_url );
    
                // Set variables for storage
                // fix file filename for query strings
                preg_match('/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $thumb_url, $matches);
                $file_array['name'] = basename($matches[0]);
                $file_array['tmp_name'] = $tmp;
    
                // If error storing temporarily, unlink
                if ( is_wp_error( $tmp ) ) {
                    @unlink($file_array['tmp_name']);
                    $file_array['tmp_name'] = '';
                }
    
                // do the validation and storage stuff
                $thumbid = media_handle_sideload( $file_array, $post->ID, $desc );
                // If error storing permanently, unlink
                if ( is_wp_error($thumbid) ) {
                    @unlink($file_array['tmp_name']);
                    return $thumbid;
                }
            }
    
            set_post_thumbnail( $post, $thumbid );
    }
    
    function youtubeid($url) {
            if (preg_match('%youtube\\.com/(.+)%', $url, $match)) {
                    $match = $match[1];
                    $replace = array("watch?v=", "v/", "vi/");
                    $match = str_replace($replace, "", $match);
                    $match = substr( $match, 0, ( strpos( $match, '&')  ) );
            }
            return $match;
    }

    http://pastebin.com/0d8MGaLb

  8. welcha4
    Member
    Posted 3 years ago #

    Justin - I am trying to do this as well but I'm having trouble using your code. I'm a php newbie so do you think you could help explain lines 20 and 43 to me? I understand what preg_match() is supposed to do but I haven't yet mastered what all the characters mean.

    I seem to be having a problem with youtubeid(). I've tested it out a few ways like this:

    echo youtubeid('http://www.youtube.com/watch?v=UcUmGzciPfo');

    or

    $url = 'http://www.youtube.com/watch?v=UcUmGzciPfo';
    $ytid = youtubeid($url);
    echo $ytid;

    Both ways are not echoing anything. Any help would be appreciated. Thanks!

  9. Justin Sternberg
    Member
    Posted 3 years ago #

    Hey welcha4,
    i've updated the youtubeid() function to use php functions to parse the url. Take a look at the new version and let me know if it helps.

    function youtubeid($url) {
        $domain = parse_url( $url, PHP_URL_HOST );
        $url = esc_url( $url );
        if ( $domain == 'www.youtube.com' || $domain == 'youtube.com' ) {
            parse_str( parse_url( $url, PHP_URL_QUERY ) );
            $youtubeid = $v;
        } else {
            $youtubeid = '';
        }
        return $youtubeid;
    }

    http://pastebin.com/xvqSvbYk

  10. Justin Sternberg
    Member
    Posted 3 years ago #

    & to answer your question, line 20 was taken from a WordPress function, and line 43 from some source online... i honestly couldn't tell you how the regular expressions worked.

  11. welcha4
    Member
    Posted 3 years ago #

    works great, thanks!

  12. welcha4
    Member
    Posted 3 years ago #

    To prevent this from creating a new thumbnail every time you edit a post, add the action to draft_to_publish instead of save_post. This will create a thumbnail only on the first time the post is published.

  13. Michelle
    Member
    Posted 3 years ago #

    Thanks everyone! @Justin Sternberg, I've updated your function to include the new youtu.be URL that users might try to use if they click "Share" in YouTube and embed that URL instead of the one in the address bar:

    function youtubeid($url) {
        $domain = parse_url( $url, PHP_URL_HOST );
        $url = esc_url( $url );
        if ( $domain == 'www.youtube.com' || $domain == 'youtube.com' ) {
            parse_str( parse_url( $url, PHP_URL_QUERY ) );
            $youtubeid = $v;
        } elseif ( $domain == 'youtu.be' ) {
            $youtubeid = substr( parse_url( $url, PHP_URL_PATH ), 1 ) ;
        } else {
            $youtubeid = '';
        }
        return $youtubeid;
    }

    Hope that's of use to someone. Thanks again.

  14. Justin Sternberg
    Member
    Posted 3 years ago #

    Awesome, thanks for that update, mmcginnis. I have included it my code.

  15. raymondsiri
    Member
    Posted 3 years ago #

    Hello Guys, I'm going through the same thing as you. I have a small production company and I want to use the youtube thumbnail as the featured image.

    Can anyone of you tell me how to use this code, where should I paste it or where I'm suppose to save it.

    Thanks very much!

  16. Justin Sternberg
    Member
    Posted 2 years ago #

    raymondsiri,
    you'll need to paste this code in functions.php or a plugin.

Topic Closed

This topic has been closed to new replies.

About this Topic