How to add a media with PHP

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