[워드프레스] 파일 업로드 코드 예제

말 그대로 예제다. 시간이 없어서 설명은 생략하고 코드만.

if( ! empty($_FILES)){
  $wp_upload_dir = wp_upload_dir();

  require_once(ABSPATH . 'wp-admin/includes/file.php');
  $fileinfo = wp_handle_upload($_FILES['첨부파일'], array('test_form' => FALSE ));
  $wp_filetype = wp_check_filetype(basename($fileinfo['file']), null );

  $attachment = array(
    'guid' => $wp_upload_dir['url'] . '/' . basename($fileinfo['file']),
    'post_mime_type' => $wp_filetype['type'],
    'post_title' => preg_replace('/\.[^.]+$/', '', basename($fileinfo['file'])),
    'post_content' => '',
    'post_status' => 'inherit'
  );

  $attach_id = wp_insert_attachment( $attachment, $fileinfo['file'], $post_id);

  require_once(ABSPATH . 'wp-admin/includes/image.php');
  $attach_data = wp_generate_attachment_metadata( $attach_id, $fileinfo['file'] );
  wp_update_attachment_metadata( $attach_id, $attach_data );
}

클라이언트 쪽은 다음 코드를 참고. 역시 시간이 없어서 foreach를 못 돌렸다. 알아서 돌리길.

$args = array(
  'post_type' => 'attachment',
  'numberposts' => null,
  'post_status' => null,
  'post_parent' => $post->ID
);
$attachments = get_posts($args);

if($attachments){?>
  <p>
    첨부파일 :
    <a href="<?=wp_get_attachment_url($attachments[0]->ID)?>">
      <?=apply_filters('the_title', $attachments[0]->post_title);?>
    </a>
  </p>
<?}?>

카테고리

17년차 풀스택 웹 개발자 안형우입니다

웹 개발에서도 중요한 것은 개념입니다.
이 블로그에는 제가 개발하며 익힌 개념들을 정리합니다.

워드프레스를 오래 다뤄 왔고 강의도 두 편 찍었습니다.
– 인프런 “워드프레스 제대로 개발하기 어드민 편, 클라이언트 편
– 클래스101 “누구나 할 수 있는 워드프레스 홈페이지 만들기 – 기획부터 출시까지 한 방에 OK

유튜브 채널에 워드프레스 관련 팁들을 올리고 있습니다.

👉 소개 더 보기

대표글

댓글 남기기