how to add Media in the Wordpress Library programmatically?

1

Consider the situation where hundreds of .jpg files are already available in the wp-content/uploads/2014/09 directory by default and need them to appear in the Media Library ( link ) of the WordPress site.

Is there any SQL script that can simply update the database or should I use a PHP script?

What's the best approach?

    
asked by anonymous 22.09.2014 / 15:18

1 answer

2

The following function was developed to import photos from another site, but can be adapted to your needs.

You could do something like this:

function _import_photo( $postid, $photo_name ) {
    $post = get_post( $postid );
    if( empty( $post ) )
        return false;

    if( !class_exists( 'WP_Http' ) )
      include_once( ABSPATH . WPINC. '/class-http.php' );

    $photo = new WP_Http();
    $photo = $photo->request( 'http://example.com/photos/directory/' . $photo_name . '.jpg' );
    if( $photo['response']['code'] != 200 )
        return false;

    $attachment = wp_upload_bits( $user_login . '.jpg', null, $photo['body'], date("Y-m", strtotime( $photo['headers']['last-modified'] ) ) );
    if( !empty( $attachment['error'] ) )
        return false;

    $filetype = wp_check_filetype( basename( $attachment['file'] ), null );

    $postinfo = array(
        'post_mime_type'    => $filetype['type'],
        'post_title'        => $post->post_title . ' employee photograph',
        'post_content'      => '',
        'post_status'       => 'inherit',
    );
    $filename = $attachment['file'];
    $attach_id = wp_insert_attachment( $postinfo, $filename, $postid );

    if( !function_exists( 'wp_generate_attachment_data' ) )
        require_once(ABSPATH . "wp-admin" . '/includes/image.php');
    $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
    wp_update_attachment_metadata( $attach_id,  $attach_data );
    return $attach_id;
}
    
22.09.2014 / 15:40