웹사이트 검색

WordPress의 URL에서 추천 이미지를 추가하는 방법


때로는 추천 이미지를 게시물에 동적으로 추가하거나 WordPress 설치가 실행 중인 서버가 아닌 다른 서버의 사용자 정의 게시물 유형을 추가해야 하는 경우도 있습니다. 그리고 여러분은 공통적인 문제에 직면해 있습니다. 어떻게 해야 할까요?

물론 이 경우에는 두 번째 서버에서 추천 이미지를 가져와 자신의 서버 업로드 폴더에 다운로드한 다음 올바른 게시물에 할당해야 합니다. 첫 번째 단계에서는 새 게시물을 동적으로 생성한 다음 추천 이미지를 처리하겠습니다.

1단계: 동적으로 게시물 만들기

게시물을 동적으로 생성하려면 wp_insert_post() 함수를 사용해야 합니다. 아래 코드를 "IF" 문에 넣을 수 있습니다. 그렇지 않으면 페이지가 로드될 때마다 새 게시물이 생성됩니다. 그다지 편리하지 않습니다.

// Register Post Data
$post = array();
$post['post_status']   = 'publish';
$post['post_type']     = 'post'; // can be a CPT too
$post['post_title']    = 'My New Post';
$post['post_content']  = 'My new post content';
$post['post_author']   = 1;

// Create Post
$post_id = wp_insert_post( $post );

이 코드를 실행하면 새 게시물이 생성됩니다. 이제 추천 이미지를 추가할 차례입니다.

2단계: 추천 이미지 추가

URL에서 추천 이미지를 추가하려면 몇 가지 WordPress 기능을 사용해야 합니다.

  • wp_upload_dir() : 업로더 폴더 경로를 검색합니다.
  • wp_mkdir_p() : 폴더 생성 및 권한 설정
  • wp_check_filetype() : 첨부파일 형식 확인
  • sanitize_file_name() : 첨부 파일 이름의 형식을 지정합니다.
  • wp_insert_attachment() : 첨부 파일 생성
  • wp_generate_attachment_metadata() : 첨부 파일 메타데이터를 생성합니다.
  • wp_update_attachment_metadata() : 첨부 파일 메타데이터를 업데이트합니다.
  • set_post_thumbnail() : 게시물 추천 이미지로 첨부 파일을 지정합니다.

이제 여기에 코드가 있습니다. 이 스크립트가 실행될 때 무슨 일이 일어나고 있는지 정확히 볼 수 있도록 각 작업에 주석을 달았습니다.

// Add Featured Image to Post
$image_url        = 'http://s.wordpress.org/style/images/wp-header-logo.png'; // Define the image URL here
$image_name       = 'wp-header-logo.png';
$upload_dir       = wp_upload_dir(); // Set upload folder
$image_data       = file_get_contents($image_url); // Get image data
$unique_file_name = wp_unique_filename( $upload_dir['path'], $image_name ); // Generate unique name
$filename         = basename( $unique_file_name ); // Create image file name

// Check folder permission and define file location
if( wp_mkdir_p( $upload_dir['path'] ) ) {
    $file = $upload_dir['path'] . '/' . $filename;
} else {
    $file = $upload_dir['basedir'] . '/' . $filename;
}

// Create the image  file on the server
file_put_contents( $file, $image_data );

// Check image file type
$wp_filetype = wp_check_filetype( $filename, null );

// Set attachment data
$attachment = array(
    'post_mime_type' => $wp_filetype['type'],
    'post_title'     => sanitize_file_name( $filename ),
    'post_content'   => '',
    'post_status'    => 'inherit'
);

// Create the attachment
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );

// Include image.php
require_once(ABSPATH . 'wp-admin/includes/image.php');

// Define attachment metadata
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );

// Assign metadata to attachment
wp_update_attachment_metadata( $attach_id, $attach_data );

// And finally assign featured image to post
set_post_thumbnail( $post_id, $attach_id );

이 코드에서 흥미로운 점은 루프에 배치할 수 있다는 것입니다. 예를 들어 CSV 파일이나 XML 파일에서 게시물을 가져옵니다. 이것은 정말 강력하고 유용하지만 한 가지를 잊지 마세요. 조건부 태그를 추가하지 않고 function.php 파일에 이 스크립트를 절대 사용하지 마세요. 그렇지 않으면 몇 분 안에 수백 개의 새 게시물이 생성될 것입니다!

이 스니펫이 유용하다고 생각하시나요? 댓글을 남겨주시고 이 스니펫으로 무엇을 만드셨는지 알려주세요!