프로그래밍 방식으로 외부에서 추천 이미지로 추천 이미지를 설정하는 방법


13

PHP를 통해 워드 프레스 환경 외부의 이미지를 가져 와서 사용자 정의 게시물에 삽입하려고합니다.

워드 프레스처럼 이미지를 워드 프레스로 업로드 / 업로드 디렉토리 연도 날짜 폴더 형식으로 이동 / 업로드하고 해당 이미지를 맞춤 게시물에 대해 추천 이미지로 설정하는 방법은 무엇입니까?

또한 맞춤 게시물 갤러리에 이미지를 업로드 하시겠습니까?

아래는 내 코드입니다

$filename = $image['name'];
$target_path = "../wp-content/uploads/";
$target_path = $target_path . $filename;
$wp_filetype = wp_check_filetype(basename($filename), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
    'guid' => $wp_upload_dir['baseurl'] . '/' . basename( $filename ),
    'post_mime_type' => $wp_filetype['type'],
    'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
    'post_content' => '',
    'post_status' => 'inherit',
);
$attach_id = wp_insert_attachment( $attachment, $target_path, $post_id );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_id, $attach_id );

이미지를 업로드 디렉토리에 업로드했지만 연도 및 날짜 폴더를 만들 수 없습니다. 이것에 대한 wp 함수가 있습니까 ??

답변:


27

media_sideload_image ()로 간단히 할 수 없습니까 ?

꽤 간단 해 보입니다. 캐치 영역에 있지 않은 경우에만 캐치해야합니다. WordPress에 다음과 같은 라이브러리가 포함되어야합니다.

// only need these if performing outside of admin environment
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');

// example image
$image = 'http://example.com/logo.png';

// magic sideload image returns an HTML image, not an ID
$media = media_sideload_image($image, $post_id);

// therefore we must find it so we can set it as featured ID
if(!empty($media) && !is_wp_error($media)){
    $args = array(
        'post_type' => 'attachment',
        'posts_per_page' => -1,
        'post_status' => 'any',
        'post_parent' => $post_id
    );

    // reference new image to set as featured
    $attachments = get_posts($args);

    if(isset($attachments) && is_array($attachments)){
        foreach($attachments as $attachment){
            // grab source of full size images (so no 300x150 nonsense in path)
            $image = wp_get_attachment_image_src($attachment->ID, 'full');
            // determine if in the $media image we created, the string of the URL exists
            if(strpos($media, $image[0]) !== false){
                // if so, we found our image. set it as thumbnail
                set_post_thumbnail($post_id, $attachment->ID);
                // only want one image
                break;
            }
        }
    }
}

1
이 솔루션은 매력처럼 작동합니다 (y)
— Omar Tariq

이 코드를 어디에 추가 할 수 있습니까?
— er.irfankhan11

1
WordPress 4.8부터 네 번째 매개 변수를 media_sideload_image로 설정할 수 'id'있으며 새 첨부 파일 ID를 반환합니다. 예 :$new_att_id = media_sideload_image($image, $post_id, "image description...", 'id'); if(!is_wp_error($new_att_id)) { set_post_thumbnail($post_id, $new_att_id); }
— Don Wilson

1

경로 및 게시물 ID를 사용하여 업로드에 대한이 설명을 시도하십시오 .

코드는 다음과 같습니다 (레거시 용).

/* Import media from url
 *
 * @param string $file_url URL of the existing file from the original site
 * @param int $post_id The post ID of the post to which the imported media is to be     attached
 *
 * @return boolean True on success, false on failure
 */

function fetch_media($file_url, $post_id) {
require_once(ABSPATH . 'wp-load.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
global $wpdb;

if(!$post_id) {
    return false;
}

//directory to import to    
$artDir = 'wp-content/uploads/2013/06';

//if the directory doesn't exist, create it 
if(!file_exists(ABSPATH.$artDir)) {
    mkdir(ABSPATH.$artDir);
}

//rename the file
$ext = array_pop(explode("/", $file_url));
$new_filename = 'blogmedia-'.$ext;

if (@fclose(@fopen($file_url, "r"))) { //make sure the file actually exists
    copy($file_url, ABSPATH.$artDir.$new_filename);


    $siteurl = get_option('siteurl');
    $file_info = getimagesize(ABSPATH.$artDir.$new_filename);

    //create an array of attachment data to insert into wp_posts table
    $artdata = array();
    $artdata = array(
        'post_author' => 1, 
        'post_date' => current_time('mysql'),
        'post_date_gmt' => current_time('mysql'),
        'post_title' => $new_filename, 
        'post_status' => 'inherit',
        'comment_status' => 'closed',
        'ping_status' => 'closed',
        'post_name' => sanitize_title_with_dashes(str_replace("_", "-", $new_filename)),                                            'post_modified' => current_time('mysql'),
        'post_modified_gmt' => current_time('mysql'),
        'post_parent' => $post_id,
        'post_type' => 'attachment',
        'guid' => $siteurl.'/'.$artDir.$new_filename,
        'post_mime_type' => $file_info['mime'],
        'post_excerpt' => '',
        'post_content' => ''
    );

    $uploads = wp_upload_dir();
            $save_path = $uploads['basedir'].'/2013/06/'.$new_filename;

    //insert the database record
    $attach_id = wp_insert_attachment( $artdata, $save_path, $post_id );

    //generate metadata and thumbnails
    if ($attach_data = wp_generate_attachment_metadata( $attach_id, $save_path)) {
        wp_update_attachment_metadata($attach_id, $attach_data);
    }

    //optional make it the featured image of the post it's attached to
    $rows_affected = $wpdb->insert($wpdb->prefix.'postmeta', array('post_id' => $post_id, 'meta_key' => '_thumbnail_id', 'meta_value' => $attach_id));
}
else {
    return false;
}

return true;
}

1

추천 이미지를 프로그래밍 방식으로 설정 한 다음 코드를 참조하십시오. http://www.pearlbells.co.uk/code-snippets/set-featured-image-wordpress-programmatically/

function setFeaturedImages() {

$base = dirname(__FILE__);
$imgfile= $base.DS.'images'.DS.'14'.DS.'Ascot_Anthracite-Grey-1.jpg';
$filename = basename($imgfile);
$upload_file = wp_upload_bits($filename, null, file_get_contents($imgfile));
if (!$upload_file['error']) {
    $wp_filetype = wp_check_filetype($filename, null );
    $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_parent' => 0,
        'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
        'post_content' => '',
        'post_status' => 'inherit'
    );
$attachment_id = wp_insert_attachment( $attachment, $upload_file['file'], 209 );

if (!is_wp_error($attachment_id)) {
    require_once(ABSPATH . "wp-admin" . '/includes/image.php');
    $attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
    wp_update_attachment_metadata( $attachment_id,  $attachment_data );
}

set_post_thumbnail( 209, $attachment_id );

}
}

0

어쩌면 내가 오해하고 있지만 왜 WordPress 환경 밖에서 그렇게하고 싶습니까? 이 기능을 복제하는 것은 많은 작업이 될 것입니다! WordPress는 단순히 파일을 업로드하여 특정 디렉토리에 배치하는 것 이상의 작업을 수행합니다. 예를 들어 파일을 업로드 할 수있는 사용자 제어, 업로드를위한 데이터베이스 레코드 추가 및 주요 이미지 관계 설정, 외부 플러그인에 대한 조치 및 필터 실행 파일 업로드-이름 지정 규칙, 미디어 업로드 위치 등의 사이트 설정을 준수하는 동안 모두.

외부 사이트에서 파일을 업로드하는 것과 같이 WordPress 관리 섹션에 로그인하지 않고 파일을 업로드하려는 경우 XML-RPC API 와 특히 uploadFile방법을 살펴볼 수 있습니다 .

또 다른 옵션은 미니 API를 직접 작성하는 것입니다. 기본적으로 당신이하고 싶은 것은 이것입니다 :

  1. 업로드를 통해 서버에서 파일을 가져 오거나 서버가 지정된 URL에서 파일을 다운로드하도록합니다.
  2. 사용하여 wp_upload_dir()업로드 디렉토리 경로를 얻을 수 및 sanitize_file_name()경로를 구성하고 그 결과 위치에 파일을 작성.
  3. wp_insert_attachment()데이터베이스에 첨부 파일을 저장하는 데 사용 합니다 ( wp_check_filetype()설정에 도움이 됨 post_mime_type). 원하는 경우 선택적으로 메타 키를 설정 post_parent하십시오 _thumbnail_id.
  4. 필요에 따라 API를 외부 사용자에게 노출하거나 로그인이 필요합니다. 최소한 공개 양식을 사용 wp_create_nonce()하고 wp_verify_nonce()양식을 조금 더 안전하게 만드는 경우.

응용 프로그램에 대한 웹 서비스를 작성 중입니다. 응용 프로그램에서 포스트 데이터와 이미지를 삽입하려는 FILE 배열을 보내십시오. 데이터베이스에 포스트 세부 정보를 삽입했지만 이미지 부분에 붙어 있습니다.
— 파이잘 자드

에 대한 설명서를 확인하십시오 wp_insert_attachment(). 필요한 일을 많이해야합니다. 당신이하는 일이라면 WordPress 외부의 데이터베이스를 수동으로 수정하지 않는 것이 좋습니다. 대신 WordPress 소스를보고 게시물 데이터 추가, 파일 업로드 처리 및 첨부 파일 삽입을 담당하는 부분을 식별하십시오. 다시 말해, 위의 답변에서 대략적으로 설명한 내용입니다.
— Simon

@Simon 나는 같은 문제가 있습니다. 업로드하려는 또 다른 이유는 다른 게시물에 첨부하고 수동으로 이미지를 첨부하지 않으려는 배치 작업이있는 경우입니다.
— hitautodestruct

1
@hitautodestruct : 물론 기존 사이트, 레거시 시스템, 데이터베이스 내보내기 등의 데이터를 마이그레이션 할 때 종종 그렇게합니다. 필자의 요점은 항상 스크립트를 작성하는 대신 WordPress 핵심 기능을 활용하여이를 달성하기 위해 노력해야한다는 것입니다. 이미지를 올바른 위치에 배치합니다 (질문과 관련하여 내가 생각한 것을 확장했습니다).
— Simon
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.