How to add Midia in Wordpress Library programmatically?

Asked

Viewed 129 times

1

Consider the situation where hundreds of files .jpg are already available in the directory wp-content/uploads/2014/09 by default and we need them to appear in the Media Library (http://meu-site.com.br/wp-admin/upload.php) of the Wordpress site.

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

What is the best approach ?

1 answer

2

The following function has been developed to import photos from another site, but can be adapted to your need.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.