How to add a media with PHP

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

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;
}

Leave a Comment