So I've written a whole bunch of functions, which are used to display Vine videos. I then have a shortcode which outputs the code.

The last thing I have to do is set the post thumbnail. I want to be able to do this automatically when the post is published.

On a Vine page, in the <head>, they have a piece of code which specifies an .jpg image of the video. I have been able to successfully grab this and upload it to the server in the uploads directory.

However, the problem is that I can't seem to be able to set that image that's been grabbed + uploaded as the post thumbnail. Either, the same attachment is given to each post (an image I manually uploaded a while ago) or it doesn't set at all.

Here's my code:

function vineThumb($id) {
    $vine = file_get_contents("http://vine.co/v/{$id}");
    preg_match('~<\s*meta\s+property="(twitter:image)"\s+content="([^"]*)~i', $vine, $matches);

    // Add Featured Image to Post
    $image_url  = $matches[2]; // Define the image URL here
    $upload_dir = wp_upload_dir(); // Set upload folder
    $image_data = file_get_contents($image_url); // Get image data
    $filename   = basename($image_url); // Create image file name

    // Check folder permission and define file location
    if( wp_mkdir_p( $upload_dir['path'] ) ) {
        $file = $upload_dir['path'] . '/' . $filename;
    } else {
        $file = $upload_dir['basedir'] . '/' . $filename;

    // Create the image  file on the server
    file_put_contents( $file, $image_data );

    /* code works up to here. Image of the just-published Vine appears in the uploads directory. I now need this image to be set as the post-thumbnail. */

    $attachments = get_posts(array(
        'numberposts' => '1', 
        'post_parent' => $post->ID, 
        'post_type' => 'attachment', 
        'post_mime_type' => 'image', 
        'order' => 'ASC'

    $attachment = $attachments[0]->ID;

    set_post_thumbnail($post->ID, $attachment);

   /* here the same attachment ID is given - if I return $attachment; it will give the same ID, so when the code runs it just uploads the same attachment to each post. */

Hope I've been clear enough - it's quite difficult to explain :)

thanks for any help :)

  • 'post_parent' => $post->ID , where $post->ID is defined ? – Shazzad Jan 24 '14 at 16:13
  • @Shazzad yeah, sorry i didn't explain that. The function will be executed in a shortcode so inside that shortcode, $post->ID is defined and works properly as I've used it in other parts of the same shortcode. – Tom Oakley Jan 24 '14 at 16:35
  • Ok, but within the vineThumb function, $post was not defined. You might need to use global $post or get_post_D() function. – Shazzad Jan 24 '14 at 18:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.