programing

워드프레스에 프로그래밍적으로 업로드하는 방법 - 파일 저장 문제

instargram 2023. 10. 14. 09:31
반응형

워드프레스에 프로그래밍적으로 업로드하는 방법 - 파일 저장 문제

제가 순환하는 데이터가 있는데, 이 데이터에는 서버에 있는 파일의 제목, 내용, 경로 및 기타 다양한 정보가 포함됩니다.

목표는 데이터를 루프에서 다음과 같은 post_meta product_image가 있는 그림으로 Worpress post를 생성하는 것입니다: add_post_meta ($post_id, '_product_image', $attach_id, true);

내 루프는 다음과 같습니다.

    while($row = $STH->fetch()) {  

        $my_post = array(
          'post_title'    => $row->title,
          'post_content'  => $row->description,
          'post_status'   => 'publish',
          'post_author'   => $current_user->ID,
          'post_category' => array(6)
        );


        // Insert the post into the database
        $post_id = wp_insert_post( $my_post );

        add_post_meta( $post_id, 'product_price', 199, true );
        add_post_meta( $post_id, 'product_sub_price', 20, true);

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

        $filename = $row->image_local_name;

        // Path to the file i want to upload into wordpress.
        $path = ABSPATH . 'add/foo/uploads/' . $row->image_local_name;  // Path to file.
        var_dump($path);

        $file_url = $row->image_url;
        $filename = $row->image_local_name;

        $wp_filetype = wp_check_filetype(basename($filename), null );

        $wp_upload_dir = wp_upload_dir();

        // Path i want to save the image(s).
        $save_path = $wp_upload_dir['basedir'] . $wp_upload_dir['subdir'] . $filename;
        var_dump($save_path);


        $attachment = array(
            'post_author' => $current_user->ID, 
            'post_date' => current_time('mysql'),
            'post_date_gmt' => current_time('mysql'),
            'post_title' => $filename, 
            'post_status' => 'inherit',
            'comment_status' => 'closed',
            'ping_status' => 'closed',
            'post_name' => $filename,                                           
            'post_modified' => current_time('mysql'),
            'post_modified_gmt' => current_time('mysql'),
            'post_parent' => $post_id,
            'post_type' => 'attachment',
            'guid' =>  $wp_upload_dir['basedir'] . $filename,   // not sure if this is correct, some advise?
            'post_mime_type' => $wp_filetype['type'],
            'post_excerpt' => '',
            'post_content' => ''
        );


        $attach_id = wp_insert_attachment( $attachment, $save_path, $post_id );

        var_dump($attach_id);

        $attach_data = wp_generate_attachment_metadata( $attach_id, $path );

        var_dump($attach_data);

        $update = wp_update_attachment_metadata( $attach_id,  $attach_data );

        var_dump($update);

        // Add the attach_id to post_meta key: product_image with the value of the attach_id
        add_post_meta( $post_id, '_product_image', $attach_id, true);
    } 

출력 : http://pastebin.com/LpNzc1pP

데이터베이스에 정확하게 저장된 것처럼 보이지만 워드프레스를 통해 생성된 이미지(예: 경주용 자동차-스터드 포함-무료 배송-매트리스-앰프 리브b.jpg)

이미지는 6가지 버전으로 저장되어 있는데 이 이미지들을 배치할 업로드/08에는 저장되어 있지 않습니다.

이미지는 여기에 저장됩니다.

/Applications/MAMP/htdocs/websites/foo.dev/public_html/add/foo/uploads/

이미지를 올바른 위치에 저장하려면 어떻게 해야 합니까?

이 코드를 100% 사용합니다.

<form method="post" enctype="multipart/form-data">
      <input type="file" name="fileToUpload">
      <input type="submit" name="upload" value="Upload">
</form>
<?php
    if(@$_POST['upload']){
                $file_name = $_FILES['fileToUpload']['name'];
                $file_temp = $_FILES['fileToUpload']['tmp_name'];

                $upload_dir = wp_upload_dir();
                $image_data = file_get_contents( $file_temp );
                $filename = basename( $file_name );
                $filetype = wp_check_filetype($file_name);
                $filename = time().'.'.$filetype['ext'];

                if ( wp_mkdir_p( $upload_dir['path'] ) ) {
                  $file = $upload_dir['path'] . '/' . $filename;
                }
                else {
                  $file = $upload_dir['basedir'] . '/' . $filename;
                }

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

                $attach_id = wp_insert_attachment( $attachment, $file );
                require_once( ABSPATH . 'wp-admin/includes/image.php' );
                $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
                wp_update_attachment_metadata( $attach_id, $attach_data );

                echo $attach_id;
            }

          ?>

나는 당신의 특정한 문제에 대한 해결책을 가지고 있지 않지만, 당신이 무엇을 달성하려고 하는지 알 수 있고, 워드프레스 API를 이용한 대체 방법을 제안합니다.media_handle_sideload()아니면media_sideload_image()는 이미지 파일을 미디어 라이브러리에 넣고 게시물에 자동으로 첨부하는 기능을 합니다.

그래서 대신:

    $filename = $row->image_local_name;

    $wp_filetype = wp_check_filetype(basename($filename), null );

    $wp_upload_dir = wp_upload_dir();

    // Path i want to save the image(s).
    $save_path = $wp_upload_dir['basedir'] . $wp_upload_dir['subdir'] . $filename;
    var_dump($save_path);


    $attachment = array(
        'post_author' => $current_user->ID, 
        'post_date' => current_time('mysql'),
        'post_date_gmt' => current_time('mysql'),
        'post_title' => $filename, 
        'post_status' => 'inherit',
        'comment_status' => 'closed',
        'ping_status' => 'closed',
        'post_name' => $filename,                                           
        'post_modified' => current_time('mysql'),
        'post_modified_gmt' => current_time('mysql'),
        'post_parent' => $post_id,
        'post_type' => 'attachment',
        'guid' =>  $wp_upload_dir['basedir'] . $filename,   // not sure if this is correct, some advise?
        'post_mime_type' => $wp_filetype['type'],
        'post_excerpt' => '',
        'post_content' => ''
    );


    $attach_id = wp_insert_attachment( $attachment, $save_path, $post_id );

    var_dump($attach_id);

    $attach_data = wp_generate_attachment_metadata( $attach_id, $path );

    var_dump($attach_data);

    $update = wp_update_attachment_metadata( $attach_id,  $attach_data );

    var_dump($update);

    // Add the attach_id to post_meta key: product_image with the value of the attach_id
    add_post_meta( $post_id, '_product_image', $attach_id, true);

다음을 사용할 수 있습니다.

$myAttachmentId = media_handle_sideload( $file_url, $post_id );

그러면 미디어 라이브러리에 이미지가 게시물의 첨부 파일로 업로드되고 다음을 통해 "제품 이미지"로 만들 수 있습니다.

$myProductImage = add_post_meta( $post_id, '_product_image', $myAttachmentId, true );

wp_insert_attachment파일을 어디로도 옮기지 않습니다.직접 올바른 폴더로 이동해야 합니다.From the WordPress Function Reference: "파일의 URI가 아닌 절대 경로를 사용합니다.파일이 업로드 디렉토리에 있어야 합니다."

를 사용하는 것을 추천합니다.wp_upload_bits함수는 블로그가 연도별/월별 디렉토리에 대해 설정되어 있는지 여부를 알고 파일의 경로와 URL을 제공하기 때문에 파일을 이동하는 기능입니다.

$upload = wp_upload_bits( $filename, null, file_get_contents($path) );
if ( $upload['error'] )
    echo "Failed uploading: " . $upload['error'];

당신의$attachment배열, 사용['guid'] => $upload['url'], 다음:

$attach_id = wp_insert_attachment( $attachment, $upload['file'], $post_id );
$attach_data = wp_generate_attachment_metadata( $attach_id, $upload['file'] );
$update = wp_update_attachment_metadata( $attach_id, $attach_data );

언급URL : https://stackoverflow.com/questions/18276169/how-to-upload-to-wordpress-programmatically-saving-files-issue

반응형