2014-05-21 5 views
4

Я создаю собственный импортер CSV для клиента, и фотографии добавляются, однако эскизы не генерируются должным образом. После использования плагина, такого как Regenerate Thumbnails, они показывают правильно.Wordpress - программно добавление продуктов, не создающих миниатюры

Вот код, в котором я добавляю вложение и связываю его с сообщением.

$uploadDir = 'wp-content/uploads/importedproductimages/'; 
    $siteurl = get_option('siteurl'); 
    $thumbnail = 'importedproductimages/' . $name; 
    $filename = 'importedproductimages/' . $name; 
    $wp_filetype = wp_check_filetype($filename, null); 
    $attachment = array(
       'post_author' => 1, 
       'post_date' => current_time('mysql'), 
       'post_date_gmt' => current_time('mysql'), 
      'post_mime_type' => $wp_filetype['type'], 
      'post_title' => $filename, 
       'comment_status' => 'closed', 
       'ping_status' => 'closed', 
      'post_content' => '', 
      'post_status' => 'inherit', 
       'post_modified' => current_time('mysql'), 
       'post_modified_gmt' => current_time('mysql'), 
       'post_parent' => $post_id, 
       'post_type' => 'attachment', 
       'guid' => $siteurl.'/'.$uploadDir.$name 
    ); 

    $attach_id = wp_insert_attachment($attachment, $filename, $post_id); 
    $attach_data = wp_generate_attachment_metadata($attach_id, $thumbnail); 
    wp_update_attachment_metadata($attach_id, $attach_data); 

    // add featured image to post 
    add_post_meta($post_id, '_thumbnail_id', $attach_id); 

Почему эскизы не генерируются должным образом? Спасибо заранее.

EDIT:

Я также включил image.php так:

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

Когда вы говорите, что не сгенерировано должным образом, что вы имеете в виду? не правильный размер? вообще не показывать? – danyo

ответ

7

Это в конечном итоге работает для меня:

  function createnewproduct($product) 
     { 


      $new_post = array(
       'post_title' => $product['Product'], 
       'post_content' => $product['Long_description'], 
       'post_status' => 'publish', 
       'post_type' => 'product' 
      ); 

      $skuu = $product['SKU']; 
      $post_id = wp_insert_post($new_post); 
      update_post_meta($post_id, '_sku', $skuu); 
      update_post_meta($post_id, '_regular_price', $product['ourPrice']); 
      update_post_meta($post_id, '_manage_stock', true); 
      update_post_meta($post_id, '_stock', $product['Qty']); 
      update_post_meta($post_id, '_weight', $product['Weight']); 
      if (((int)$product['Qty']) > 0) { 
       update_post_meta($post_id, '_stock_status', 'instock'); 
      } 


      $dir = dirname(__FILE__); 
      $imageFolder = $dir.'/../import/'; 
      $imageFile = $product['ID'].'.jpg'; 
      $imageFull = $imageFolder.$imageFile; 

      // 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://localhost/wordpress/wp-content/import/'.$product['ID'].'.jpg'; 

      // 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; 
         } 
        } 
       } 
      } 
     } 
+0

Когда вы удаляете изображение, я не думаю, что он проходит через обычный процесс создания всех промежуточных эскизов. Может оказаться полезной функция [image_make_intermediate_size() ') (http://codex.wordpress.org/Function_Reference/image_make_intermediate_size). – helgatheviking

0

Старый вопрос, я знаю, но это придумал на Google в моих поисках ответа, и есть лучший способ генерации эскизов, а также любые другие требуемые размеры изображений: wp_generate_attachment_meta. Используется в двух строках:

$attach_data = wp_generate_attachment_metadata($attach_id, $filename); 
wp_update_attachment_metadata($attach_id, $attach_data); 

Это обновит все размеры изображений, включая эскизы, при данных крепежном ID.

Смежные вопросы