2016-06-29 3 views
0

원격 서버에서 이미지를 가져 와서 사용자 정의 필드로 설정하려고합니다. 첨부 파일 ID 가져 오기 및 생성이 작동하지만 사용자 정의 필드가 엉망입니다. 스레드 문제 또는 뭔가 있는지 나는 모르겠다.원격 이미지를 Wordpress로 가져온 다음 사용자 정의 필드로 설정하십시오.

$sql = 'SELECT * FROM produto'; 
$retval = mysql_query($sql, $connection) ; 

while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) 
{ 

    $file = $row['imagem']; 
    $filename = basename($file); 
    $upload_file = wp_upload_bits($filename, null, file_get_contents($file)); 
    if (!$upload_file['error']) { 
     $wp_filetype = wp_check_filetype($filename, null); 
     $attachment = array(
      'post_mime_type' => $wp_filetype['type'], 
      'post_parent' => $parent_post_id, 
      'post_title' => preg_replace('/\.[^.]+$/', '', $filename), 
      'post_content' => '', 
      'post_status' => 'inherit' 
     ); 
     $attachment_id = wp_insert_attachment($attachment, $upload_file['file'], $parent_post_id); 

     $imgs[$row['modelo']][]['imagem'] = $attachment_id; 

     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); 

     } 
    } 

} 

foreach ($imgs as $key => $value) { 

    $args = array(
    'post_type' => 'produto', 
    'meta_key' => 'identifier1', 
    'meta_value' => $key); 
    // The Query 
    $the_query = new WP_Query($args); 
    if ($the_query->have_posts()) { 
     while ($the_query->have_posts()) { 
      $the_query->the_post(); 
      update_field('imagens', $value, get_the_ID()); 
     } 
    } 
    /* Restore original Post Data */ 
    wp_reset_postdata(); 

} 

나는이 사용자 정의 필드에 20 itens를 설정하려고하면, 그것은 완벽하게 작동합니다 :

여기 내 코드입니다. 하지만이 루프를 250 개의 결과로 실행해야하는 경우에는 중단됩니다.

내가 뭘 잘못하고 있니?

감사합니다!

답변

0

하나의 비 wp 데이터베이스를 wp 준비 데이터베이스로 마이그레이션해야했으며 데이터베이스에는 10,000 개 이상의 이미지가있었습니다. 또한 가져 오기를 한꺼번에 수행하도록 설정했습니다 (방금 게시물뿐만 아니라 이미지 및 모든 메타 데이터, 페이지 등도 업로드했습니다).

일을 한꺼번에 가져 오는 것이 서버 시간 초과 가능성이 가장 높으며 처음으로 가져온 이미지가 일 뿐이며 나머지는 시간 초과 또는 유사한 오류로 인해 작동하지 않습니다.

해결 방법은 스크립트를 AJAX로 호출 할 함수에 넣고 한 번에 하나의 이미지를 가져 오는 것입니다.에 이미지 하나를 가져 오려면 약간 조정할 필요가 있습니다.

먼저 $imgs 어레이가 가득 찼는 지 확인합니다. 이전 데이터베이스의 모든 이미지가 첨부 된 모든 데이터와 함께 표시됩니다. 이 경우

, 당신은 그럼 당신은 AJAX를 사용하여이 함수를 호출 할 수 있습니다이

<?php 

add_action('wp_ajax_import_image', 'import_image_callback'); 
add_action('wp_ajax_nopriv_import_image', 'import_image_callback'); // this is only if you're importing from the front end. If in the back end this is not necessary 


/** 
* AJAX callback iumport image function 
* 
*/ 
function import_image(){ 

    $img = $_POST['img']; 

    $args = array(
     'post_type' => 'produto', 
     'meta_key' => 'identifier1', 
     'meta_value' => $img 
    ); 
    // The Query 
    $image_query = new WP_Query($args); 
    if ($image_query->have_posts()) { 
     while ($image_query->have_posts()) { 
      $image_query->the_post(); 
      update_field('imagens', $img['image_value'], get_the_ID());//You'll need to see what you need from the array value here, I just placed dummy image_value as I don't know what the $img array contains 
     } 
    } 
    /* Restore original Post Data */ 
    wp_reset_postdata(); 
} 

같은 것을 추가해야합니다. 이제 이미지를 JSON 객체 및 localize it으로 저장해야 할 것입니다. 이 같은으로 한 번에 하나의 이미지를 가져 오기 위해 자바 스크립트에서 그 배열을 사용 할 수 있습니다 그런 식 : 나는 당신의 DB 덤프는 다음과 같습니다 방법을 알고하지 않기 때문에 지금

jQuery(document).ready(function($) { 
    "use strict"; 

    var images = localized_object.images_array; //JSON array 

    for (var i = 0; i < images.length; i++) { 
     var img = images[i]; //something like this - you'll see if this works 100%, but the gist is the same 

     upload_image(img); // Call the AJAX callback function 
    } 


    function upload_image(image){ 
     $.ajax({ 
      type: "POST", 
      url: localized_object.ajaxurl, //localize this if you're doing this from the from the front end. If you're using it in back end just use ajaxurl. 
      data: { 
       'action': 'import_image', 
       'img': image, 
      }, 
      success: function(response) { 
       console.log('Image imported'); 
      }, 
      error : function (jqXHR, textStatus, errorThrown) { 
       console.log(jqXHR + ' :: ' + textStatus + ' :: ' + errorThrown); 
      } 
     }); 
    } 
}); 

100 아니다 %는 일을 할 수 있지만, 어떻게하면 좋은지 알 수 있습니다.

희망이 있습니다.

+0

안녕하세요, 답장을 보내 주셔서 감사합니다. 나는 당신의 기능과 그것이 취하는 흐름을 얻었습니다. 그러나 MySQL 쿼리는 어디에 두어야합니까? 이 방법으로 js 객체에 이미지 배열이 있다고 가정하지만 db에서 가져와야합니다. –

+0

그럼 데이터베이스에서 모든 이미지를 가져와야합니다 (예를 들어'$ wpdb-> get_results'로). wpdb를 사용하면 결과를 객체 또는 배열로 정렬 할 수 있으므로 배열을 선택한 다음 ['json_encode']로 json으로 '변환'할 수 있습니다 (http://php.net/manual/en/function.json-encode .php), 그 값을 지역화 함수에서 지역화 할 수 있습니다. 또는 숨겨진 div에 넣으십시오. 자바 스크립트에서 가져올 수 있습니다. (지역화를 원하지 않는다면 ...) –

+0

내'imagens' 사용자 정의 필드를 업데이트하려고 할 때 문제가 발생한다는 것을 깨달았습니다. 원격 이미지 가져 오기 및 WordPress에 업로드 잘 작동하지만, 쿼리 사용자 정의 필드를 업데이 트하는 과정은 어느 시점에서 휴식. –

관련 문제