2

I have more than 1000 pictures on my webserver, uploaded with FTP in a local folder ( /home/chris/pictures )

Is there a way to add them as a well known media to wordpress in PHP and get their id?

while ( $the_query->have_posts() ) : $the_query->the_post();
    $post_id = get_the_ID();
    $filemakerID = get_post_meta($post_id, 'filemaker_id', true);

    $file['url']='/home/chris/picture_export/'.$filemakerID.'.jpeg';
    $file['type'] = 'image/jpeg';

    //THE DREAMED FUNCTION WOULD BE USED THIS WAY
    $photo_id = awesome_function( $file, $post_id);

    add_post_meta($post_id, 'photo', $photo_id );
}

As you noticed, my photo is used in a custom field photo as well.

After hours on google dans codex, I noticed how poorly documented these functions are. Maybe I just could not figure out the correct keywords to search.

1 Answer 1

5

If I'm understanding correctly, each post has a filemaker, and each filemaker has only one photo? The structure is kind of unclear.

Anyways, one way is top use media_sideload_image like below.

However, media_sideload_image WON'T work with local files (a path on your filesystem), so you need to change your $file['url'] to be a valid URL (http://yourhomepage.com/chris/pictures, for example). If you can't do that, you need to use wp_upload_bits and wp_insert_attachment, but that way is a lot more work/harder.

function awesome_function($file, $post_id) {

    require_once(ABSPATH . 'wp-admin' . '/includes/image.php');
    require_once(ABSPATH . 'wp-admin' . '/includes/file.php');
    require_once(ABSPATH . 'wp-admin' . '/includes/media.php');

    // upload image to server
    media_sideload_image($file['url'], $post_id);

    // get the newly uploaded image
    $attachments = get_posts( array(
        'post_type' => 'attachment',
        'number_posts' => 1,
        'post_status' => null,
        'post_parent' => $post_id,
        'orderby' => 'post_date',
        'order' => 'DESC',) 
    );

    // returns the id of the image
    return $attachments[0]->ID;
}
3
  • Actually your answer is so simple that it IS awesome :). Sadly I got errors Fatal error: Call to undefined function media_sideload_image() so I added require_once( '....../wp-admin/includes/media.php'); and now got a follow error: 'Fatal error: Call to undefined function download_url() in ......./wp-admin/includes/media.php on line 598' I keep trying
    – Christian
    Commented Aug 16, 2012 at 8:06
  • 3
    Try including /wp-admin/includes/media.php, /wp-admin/includes/file.php and /wp-admin/includes/image.php and see if that works.
    – pbd
    Commented Aug 16, 2012 at 8:09
  • 1
    worked with these 3 require_once . Thank you so much.
    – Christian
    Commented Aug 16, 2012 at 8:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.