programing

URL에서 이미지를 다운로드하여 WordPress 미디어 라이브러리에 업로드합니다.

elecom 2023. 10. 25. 22:34
반응형

URL에서 이미지를 다운로드하여 WordPress 미디어 라이브러리에 업로드합니다.

이미지 URL을 찍어 이미지를 다운로드하여 미디어 라이브러리에 업로드하고 이미지 ID를 반환하는 워드프레스 기능을 구축하려고 합니다.

여기서 얻은 답변을 그대로 차용해서 wp_insert_attachment()를 마지막에 추가했습니다.

현재로서는 아무것도 반환하지 않거나 미디어를 업로드하지 않기 때문에 작동하지 않습니다.

디딤으로써 디버깅에 지쳤습니다.var_dump(), 그리고 나는 그것을 발견했습니다.$url매개 변수가 올바르게 전달되었지만 아무 것도 출력되지 않습니다.download_url.

무엇이 잘못되었는지 알고 있습니까?

기능이 깨질 수도 있는 다른 것이 보이나요?

/* Add image to media library from URL and return the new image ID */
function bg_image_upload($url) {

  // Gives us access to the download_url() and wp_handle_sideload() functions
  require_once( ABSPATH . 'wp-admin/includes/file.php' );

  // Download file to temp dir
  $timeout_seconds = 10;
  $temp_file = download_url( $url, $timeout_seconds );

  if ( !is_wp_error( $temp_file ) ) {

      // Array based on $_FILE as seen in PHP file uploads
      $file = array(
          'name'     => basename($url), // ex: wp-header-logo.png
          'type'     => 'image/png',
          'tmp_name' => $temp_file,
          'error'    => 0,
          'size'     => filesize($temp_file),
      );

      $overrides = array(
          // Tells WordPress to not look for the POST form
          // fields that would normally be present as
          // we downloaded the file from a remote server, so there
          // will be no form fields
          // Default is true
          'test_form' => false,

          // Setting this to false lets WordPress allow empty files, not recommended
          // Default is true
          'test_size' => true,
      );

      // Move the temporary file into the uploads directory
      $results = wp_handle_sideload( $file, $overrides );

      if ( !empty( $results['error'] ) ) {
          // Insert any error handling here
      } else {

          $filename  = $results['file']; // Full path to the file
          $local_url = $results['url'];  // URL to the file in the uploads dir
          $type = $results['type']; // MIME type of the file
          $wp_upload_dir = wp_upload_dir(); // Get the path to the upload directory.

          $attachment = array (
            'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
            'post_mime_type' => $type,
            'post_status' => 'inherit',
            'post_content' => '',
          );

          $img_id = wp_insert_attachment( $attachment, $filename  );

          return $img_id;
      }
  }
}

100% 이 코드를 사용

include_once( ABSPATH . 'wp-admin/includes/image.php' );
$imageurl = '<IMAGE URL>';
$imagetype = end(explode('/', getimagesize($imageurl)['mime']));
$uniq_name = date('dmY').''.(int) microtime(true); 
$filename = $uniq_name.'.'.$imagetype;

$uploaddir = wp_upload_dir();
$uploadfile = $uploaddir['path'] . '/' . $filename;
$contents= file_get_contents($imageurl);
$savefile = fopen($uploadfile, 'w');
fwrite($savefile, $contents);
fclose($savefile);

$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
    'post_mime_type' => $wp_filetype['type'],
    'post_title' => $filename,
    'post_content' => '',
    'post_status' => 'inherit'
);

$attach_id = wp_insert_attachment( $attachment, $uploadfile );
$imagenew = get_post( $attach_id );
$fullsizepath = get_attached_file( $imagenew->ID );
$attach_data = wp_generate_attachment_metadata( $attach_id, $fullsizepath );
wp_update_attachment_metadata( $attach_id, $attach_data ); 

echo $attach_id;

업데이트된 코드 : 웹사이트의 루트 디렉터리에 파일을 만듭니다.코드 아래에 추가합니다.이미지의 url을 사용하여 이미지 URL을 변경합니다.

<?php 
include( 'wp-load.php' );
include_once( ABSPATH . '/wp-admin/includes/image.php' );

$imageurl = 'IMAGEURL';
$imagetype = end(explode('/', getimagesize($imageurl)['mime']));
$uniq_name = date('dmY').''.(int) microtime(true); 
$filename = $uniq_name.'.'.$imagetype;

$uploaddir = wp_upload_dir();
$uploadfile = $uploaddir['path'] . '/' . $filename;
$contents= file_get_contents($imageurl);
$savefile = fopen($uploadfile, 'w');
fwrite($savefile, $contents);
fclose($savefile);

$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
    'post_mime_type' => $wp_filetype['type'],
    'post_title' => $filename,
    'post_content' => '',
    'post_status' => 'inherit'
);

$attach_id = wp_insert_attachment( $attachment, $uploadfile );
$imagenew = get_post( $attach_id );
$fullsizepath = get_attached_file( $imagenew->ID );
$attach_data = wp_generate_attachment_metadata( $attach_id, $fullsizepath );
wp_update_attachment_metadata( $attach_id, $attach_data ); 

echo $attach_id;
 ?>

언급URL : https://stackoverflow.com/questions/52789439/download-image-from-url-and-upload-to-wordpress-media-library

반응형