Viewing 14 replies - 1 through 14 (of 14 total)
  • What do you mean by auto import? Are you expecting WP to check a photo folder on a regular base and upload any new photos it finds?

    Thread Starter Curtis

    (@curtis782)

    @aurovrata
    Thanks for your reply. The challenge I have now is that I only found a way to associate images previously uploaded to WordPress’s library with my posts. In a test, I noted the image IDs and stored them in a custom field (cf47rs_images). For example, “107, 204, 301”. When I import, the plugin “Divide Meta Fields with Comma (Really Simple CSV Importer add-on)” converts this to an array and the post successfully displays the images in my post…

    What I would like to do is in the “cf47rs_images” field, reference something like “https://localhost/websitename/photos/photo12345-1.jpg, https://localhost/websitename/photos/photo12345-2.jpg, https://localhost/websitename/photos/photo12345-3.jpg” and during import, have WordPress upload these and store the IDs automatically.
    – The photos themselves can change over time, but the filenames will not, so I would like to prevent creating duplicates (if possible). It is okay to overwrite existing files however (preferred, in case photos get updated).
    – I just need the full size photos (no need for multiple size variations that WordPress generates).

    I am running a local server and using “https://localhost/…” in the image names hoping that this can be a ‘trick’ to make WordPress think it is an external image. I know some import scripts can automatically upload external images from a URL and reference the image IDs.

    Any help with this would be greatly appreciated — thanks!

    • This reply was modified 8 years, 1 month ago by Curtis.

    associate images previously uploaded to WordPress’s library with my posts. In a test, I noted the image IDs and stored them in a custom field (cf47rs_images). For example, “107, 204, 301”. When I import, the plugin “Divide Meta Fields with Comma (Really Simple CSV Importer add-on)” converts this to an array and the post successfully displays the images in my post…

    I understand by this that what you seek to do is associate multiple images to a given post.

    What I would like to do is in the “cf47rs_images” field, reference something like “https://localhost/websitename/photos/photo12345-1.jpg, https://localhost/websitename/photos/photo12345-2.jpg, https://localhost/websitename/photos/photo12345-3.jpg” and during import, have WordPress upload these and store the IDs automatically.

    sure, you can do this, but you will need to hook into the import process using the really_simple_csv_importer_save_meta filter. Format your CSV field cf47rs_images as,

    https://localhost/websitename/photos/photo12345-1.jpg|https://localhost/websitename/photos/photo12345-2.jpg|https://localhost/websitename/photos/photo12345-3.jpg

    then place this code in your funtions.php file,

    add_filter( 'really_simple_csv_importer_save_meta', 'rsc_import_images',10,3);
    function rsc_import_images( $meta, $post, $is_update ) {
      //convert to an array
      $images = explode("|",$meta['cf47rs_images']);
      $meta['cf47rs_images']=array();//reset the meta field
    
      //directory to import images to
      $artDir = 'wp-content/uploads/imported_cf47rs_images/';
    
      //if the directory doesn't exist, create it
      if(!file_exists(ABSPATH.$artDir)) {
        mkdir(ABSPATH.$artDir);
      }
    
      require_once(ABSPATH . 'wp-load.php');
      require_once(ABSPATH . 'wp-admin/includes/image.php');
      global $wpdb;
    
      //loop through each photos that need to be imported
      foreach($images as $file_url){
        //let's get the image file name
        $new_filename = array_pop(explode("/", $file_url));
    
        //move the file to our custom import folder
        if (@fclose(@fopen($file_url, "r"))) { //make sure the file actually exists
          $siteurl = get_option('siteurl');
          $skip_attachment_insert=false;
          //check if this image has already been imported,
          if(file_exists(ABSPATH.$artDir.$new_filename) ){ //file already imported
            //either change the name of the file  UNCOMMENT the following line
            //$new_filename = date("Y-m-d H:i:s").$new_filename;
    
            //.... or overwrite it, COMMENT OUT the next 3 lines of code if you choose to uncomment the renaming of file name above.
            //in which case we want to find the attachment ID and store it in our meta field
            $attach_id = attachment_url_to_postid($siteurl.'/'.$artDir.$new_filename);
            $meta['cf47rs_images'][] = $attach_id;
            //no need to insert a new attachment, we reuse the same
            $skip_attachment_insert=true;
          }
          //(over)write the new file
          copy($file_url, ABSPATH.$artDir.$new_filename);
    
          if($skip_attachment_insert) continue;
    
          $file_info = getimagesize(ABSPATH.$artDir.$new_filename);
    
          //create an array of attachment data to insert into wp_posts table
          $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_type' => 'attachment',
            'guid' => $siteurl.'/'.$artDir.$new_filename,
            'post_mime_type' => $file_info['mime']
          );
    
          $uploads = wp_upload_dir();
          $save_path = $uploads['basedir'].'/imported_cf47rs_images/'.$new_filename;
    
          //insert the database record
          $attach_id = wp_insert_attachment( $artdata, $save_path );
          $meta['cf47rs_images'][] = $attach_id;
    
          //generate metadata and thumbnails, comment this out if you don't want thumbnails
          if ($attach_data = wp_generate_attachment_metadata( $attach_id, $save_path)) {
            wp_update_attachment_metadata($attach_id, $attach_data);
          }
        }
      }
      return $meta;
    }
    

    I have commented the code as much as possible. Note that the code will overwrite existing images if the files names are the same. The meta field in your post will have the following structure,

    Thread Starter Curtis

    (@curtis782)

    @aurovrata
    Thanks for your detailed reply. I unfortunately ran into some issues. I am assuming that it is okay to add this code as another custom add-on plugin? If so, I created this as #1 below.

    Custom Image Uploader (Really Simple CSV Importer add-on)
    This is the same code you provided in your reply.

    I also have these add-ons:

    Divide Meta Fields with Comma (Really Simple CSV Importer add-on)

    add_filter('really_simple_csv_importer_save_meta', function($meta, $post, $is_update) {
        foreach ($meta as $key => $value) {
            if (strpos($value, ',') !== false) {
                $_value = preg_split("/,+/", $value);
                $meta[$key] = $_value;
            }
        }
        return $meta;
    }, 10, 3);

    Divide Meta Fields with Double-pipe (Really Simple CSV Importer add-on)

    add_filter('really_simple_csv_importer_save_meta', 'address_to_array',10,3);
    
    function address_to_array($meta, $post, $is_update){
      $address = $meta['cf47rs_map_location'];
      $address = explode('||',$address);
      $meta_arr = array();
      foreach($address as $sub){
        $sub = explode('|',$sub);
        $meta_arr[$sub[0]] = $sub[1];
      }
      $meta['cf47rs_map_location'] = $meta_arr;
      return $meta;
    }

    My data for the cf47rs_images column is in the format:
    https://localhost/mysite/photos/photo1234567-1.jpeg|https://localhost/mysite/photos/photo1234567-2.jpeg|https://localhost/mysite/photos/photo1234567-3.jpeg|https://localhost/mysite/photos/photo1234567-4.jpeg|https://localhost/mysite/photos/photo1234567-5.jpeg

    When I import the .csv file, I get the following error (repeated for each record):

    Warning: strpos() expects parameter 1 to be string, array given in /home/myaccountname/public_html/mydomain.com/wp-content/plugins/divide-meta-fields-with-comma/divide-meta-fields-with-comma.php on line 7
    
    Warning: preg_split() expects parameter 2 to be string, array given in /home/myaccountname/public_html/mydomain.com/wp-content/plugins/divide-meta-fields-with-comma/divide-meta-fields-with-comma.php on line 8
    
    Warning: explode() expects parameter 2 to be string, array given in /home/myaccountname/public_html/mydomain.com/wp-content/plugins/divide-meta-fields-with-double-pipe/divide-meta-fields-with-double-pipe.php on line 14
    
    Warning: Invalid argument supplied for foreach() in /home/myaccountname/public_html/mydomain.com/wp-content/plugins/divide-meta-fields-with-double-pipe/divide-meta-fields-with-double-pipe.php on line 16
    Processing "123 Main Street, City, ST 12345" done.

    When I the database record, I do not see any of the images referenced (URL, path, or IDs) and no images are uploaded to /public_html/mydomain.com/wp-content/uploads/imported_cf47rs_images
    …although the “imported_cf47rs_images” directory was created.`

    Do you have any suggestions on how I can approach this issue? Thanks!

    • This reply was modified 8 years, 1 month ago by Curtis.
    • This reply was modified 8 years, 1 month ago by Curtis.
    • This reply was modified 8 years, 1 month ago by Curtis.

    you should not mix the 2 codes. Please follow the instructions I gave you in my answer above. You can insert it at the bottom of your functions.php file to try it first.

    the ‘Divide Meta Fields with Comma (Really Simple CSV Importer add-on)’ add-on is causing the problem I reckon. Remove it.

    Thread Starter Curtis

    (@curtis782)

    @aurovrata
    I have removed the add-on plugins and placed your code at the end of my theme’s functions.php file. I ran the import again and there were no errors after the import, but the images did not upload and the value in the database for cf47rs_images appeared as “a:0:{}” (without quotes). I entered the photo values in my import exactly as “https://localhost/websitename/photos/photo12345-1.jpg|https://localhost/websitename/photos/photo12345-2.jpg|https://localhost/websitename/photos/photo12345-3.jpg” (without quotes) without luck. I then tried with quotes around this, and that did not work. Do you have any other suggestions I can try? Thanks!

    Thread Starter Curtis

    (@curtis782)

    I ran the debugger script at https://gist.github.com/hissy/7175656 and noticed this output (partial provided to save space):

    $is_update:
    bool(true)
    $post:
    array(9) {
      ["post_type"]=>
      string(15) "cf47rs_mypostsample"
      ["ID"]=>
      string(7) "123456789"
      ["post_name"]=>
      string(34) "Post name here"
      ["post_author"]=>
      int(3)
      ["post_date"]=>
      string(19) "2015-01-01 00:00:00"
      ["post_status"]=>
      string(7) "publish"
      ["post_title"]=>
      string(36) "1 Main Street, City, ST 12345"
      ["post_content"]=>
      string(892) "Content here..."
      ["post_category"]=>
      array(1) {
        [0]=>
        string(2) "97"
      }
    }
    $meta:
    array(18) {
      ...various here...
      ["field_cf47rs_mypostsample_add_to_gallery"]=>
      string(0) ""
      ["cf47rs_map_location"]=>
      string(92) "address|1 Main Street, City, ST 12345, United States||lat|40.123456789||lng|-70.123456789"
      ["_cf47rs_map_location"]=>
      string(34) "field_cf47rs_property_map_location"
      ["photo_count"]=>
      string(2) "18"
      ["cf47rs_images"]=>
      array(0) {
      }
      ["_cf47rs_images"]=>
      string(27) "field_cf47rs_gallery_images"
      ["field_cf47rs_mypostsample_tour"]=>
      string(0) ""
    }
    $tax:
    array(0) {
    }

    your meta[] values are not loading the field ‘cf47rs_images’ values

    ["cf47rs_images"]=> array(0) { }

    Which is why you are getting an empty array in your db. Can you run the following modified code I posted,

    
    add_filter( 'really_simple_csv_importer_save_meta', 'rsc_import_images',10,3);
    function rsc_import_images( $meta, $post, $is_update ) {
      var_dump($meta['cf47rs_images'], 'imported image field...');
      //convert to an array
      $images = explode("|",$meta['cf47rs_images']);
      var_dump($imagges, 'converted image array ...');
      $meta['cf47rs_images']=array();//reset the meta field
    
      //directory to import images to
      $artDir = 'wp-content/uploads/imported_cf47rs_images/';
    
      //if the directory doesn't exist, create it
      if(!file_exists(ABSPATH.$artDir)) {
        mkdir(ABSPATH.$artDir);
      }
    
      require_once(ABSPATH . 'wp-load.php');
      require_once(ABSPATH . 'wp-admin/includes/image.php');
      global $wpdb;
    
      //loop through each photos that need to be imported
      foreach($images as $file_url){
        //let's get the image file name
        $new_filename = array_pop(explode("/", $file_url));
    
        //move the file to our custom import folder
        if (@fclose(@fopen($file_url, "r"))) { //make sure the file actually exists
          $siteurl = get_option('siteurl');
          $skip_attachment_insert=false;
          //check if this image has already been imported,
          if(file_exists(ABSPATH.$artDir.$new_filename) ){ //file already imported
            //either change the name of the file  UNCOMMENT the following line
            //$new_filename = date("Y-m-d H:i:s").$new_filename;
    
            //.... or overwrite it, COMMENT OUT the next 3 lines of code if you choose to uncomment the renaming of file name above.
            //in which case we want to find the attachment ID and store it in our meta field
            $attach_id = attachment_url_to_postid($siteurl.'/'.$artDir.$new_filename);
            $meta['cf47rs_images'][] = $attach_id;
            //no need to insert a new attachment, we reuse the same
            $skip_attachment_insert=true;
          }
          //(over)write the new file
          copy($file_url, ABSPATH.$artDir.$new_filename);
    
          if($skip_attachment_insert) continue;
    
          $file_info = getimagesize(ABSPATH.$artDir.$new_filename);
    
          //create an array of attachment data to insert into wp_posts table
          $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_type' => 'attachment',
            'guid' => $siteurl.'/'.$artDir.$new_filename,
            'post_mime_type' => $file_info['mime']
          );
    
          $uploads = wp_upload_dir();
          $save_path = $uploads['basedir'].'/imported_cf47rs_images/'.$new_filename;
    
          //insert the database record
          $attach_id = wp_insert_attachment( $artdata, $save_path );
          $meta['cf47rs_images'][] = $attach_id;
          var_dump($save_path, 'inserted image as attachment '.$attach_id);
          //generate metadata and thumbnails, comment this out if you don't want thumbnails
          if ($attach_data = wp_generate_attachment_metadata( $attach_id, $save_path)) {
            wp_update_attachment_metadata($attach_id, $attach_data);
          }
        }
      }
      return $meta;
    }

    this should print out the import filter steps. If the imported $meta['cf47rs_images'] field is empty then it means that there is an error with your csv file format.

    Thread Starter Curtis

    (@curtis782)

    @aurovrata
    Thanks very much for this code. I tried using this and it failed, so seeing your last comment in your reply, I had another look at my CSV file. It seems that I cannot use https://localhost/… in the photo URLs. I uploaded the photos elsewhere via a https://www.mydomain.com address and the photos successfully uploaded and became associated with my post then.

    Just a few small concerns/questions below I was wondering about?

    Concern #1- Is there a way that I can force the system to import from my local system, either from a local C:\ path, or via https://localhost/… ?

    Concern #2-

    In my FTP client, when I looked at the imported_cf47rs_images/ directory on my server, I saw the files as:
    photo12345-1.jpeg
    photo12345-2.jpeg
    photo12345-3.jpeg
    photo12345-4.jpeg

    This is expected behavior as I commented out the thumbnail generation code at the end of your code. When I performed a subsequent import to test the re-write function, I saw the same list (expected). However, I found a slight issue when after importing, if I go to my post and refresh the page, the system generates thumbnails. The list then becomes:

    photo12345-1-1170×600-c-center.jpeg
    photo12345-1-1740×960-c-center.jpeg
    photo12345-1-270×180-c-center.jpeg
    photo12345-1.jpeg
    photo12345-2-1170×600-c-center.jpeg
    photo12345-2-1740×960-c-center.jpeg
    photo12345-2-270×180-c-center.jpeg
    photo12345-2.jpeg
    photo12345-3-1170×600-c-center.jpeg
    photo12345-3-1740×960-c-center.jpeg
    photo12345-3-270×180-c-center.jpeg
    photo12345-3.jpeg
    photo12345-4-1170×600-c-center.jpeg
    photo12345-4-1740×960-c-center.jpeg
    photo12345-4-270×180-c-center.jpeg
    photo12345-4.jpeg

    In the WordPress Dashboard, in Settings > Media, I have the following settings:
    Thumbnail size – Width: 0, Height: 0, Crop thumbnail… (unchecked)
    Medium size – Max Width: 0, Max Height: 0
    Large size – Max Width: 0, Max Height: 0
    Uploading files – Organize my uploads into month… (unchecked)

    Perhaps the thumbnail generation is happening from code in the theme? If so, is there a way you know that can force prevent thumbnails from getting generated at the theme level?

    ——
    Update: for the last question, some people might be interested in this, but I just saw these additional images are needed for my theme to work correctly. Do you know of a way I can generate these specific thumbnails during import as well?

    If I use your code as is, it generates thumbnail as follows:
    photo12345-1-768×576.jpeg
    photo12345-1.jpeg
    photo12345-2-768×576.jpeg
    photo12345-2.jpeg
    photo12345-3-768×576.jpeg
    photo12345-3.jpeg
    photo12345-4-768×576.jpeg
    photo12345-4.jpeg

    And upon going to my post and refreshing, the system retains these thumbnails, in addition to generating the ones needed for my theme.

    Thanks again!

    • This reply was modified 8 years ago by Curtis.
    • This reply was modified 8 years ago by Curtis.
    Thread Starter Curtis

    (@curtis782)

    I could be wrong, but after looking at the local image sourcing further, it appears the images need to be hosted online rather than on my local system for this to work. WP All Import also has this limitation (https://www.wpallimport.com/documentation/images/local-computer/).

    For the thumbnail generation, I tried this code but it is not quite what I need (I need to append the “-c-center” to the end of the file name somehow to match my list above – i.e. photo12345-1-1170×600-c-center.jpeg, photo12345-1-1740×960-c-center.jpeg, photo12345-1-270×180-c-center.jpeg):

    //generate metadata and thumbnails, comment this out if you don't want thumbnails
    if ($attach_data = wp_generate_attachment_metadata( $attach_id, $save_path)) {
      //wp_update_attachment_metadata($attach_id, $attach_data);
      add_image_size( '1170×600', 1170, 600, array( 'left', 'top' ) ); // 1170×600
      add_image_size( '1740×960', 1740, 960, array( 'left', 'top' ) ); // 1740×960
      add_image_size( '270×180', 270, 180, array( 'left', 'top' ) ); // 270×180
    }

    Is it possible to do this somehow?

    Thank you

    Thread Starter Curtis

    (@curtis782)

    @aurovrata / any others:

    Just wondering if you might have any new info on how I might be able to handle the custom photo thumbnail names?

    Thanks!

    Thanks very much for this code. I tried using this and it failed, so seeing your last comment in your reply, I had another look at my CSV file. It seems that I cannot use https://localhost/… in the photo URLs. I uploaded the photos elsewhere via a https://www.mydomain.com address and the photos successfully uploaded and became associated with my post then.

    Makes sense, I was assuming you were testing this on your local machine. https://localhost/.. only works on your local machine, think about it, a domain name such as google.com is mapped to an IP address by the registrar of that domain. How is localhost mapped to your local machines IP address??? So in short,

    Concern #1- Is there a way that I can force the system to import from my local system, either from a local C:\ path, or via https://localhost/… ?

    No.

    Perhaps the thumbnail generation is happening from code in the theme? If so, is there a way you know that can force prevent thumbnails from getting generated at the theme level?

    That’s correct, either your theme or one of your plugins is responsible for the thumbnails. There are ways to stop this, but one would need to study your installation code. However, it is beyond the scope of this support thread.

    My suggestion would be that you hire a WordPress developer to help you with your requirements.

    Thread Starter Curtis

    (@curtis782)

    Thanks for the clarification. I was able to find a way around this working with the theme’s developer. For anyone that is interested:

    After:
    $attach_id = wp_insert_attachment( $artdata, $save_path );

    Add:

    $url = wp_get_attachment_url($attach_id);
    \Timber\ImageHelper::resize($url, $width, $height, $crop);

    You can then adjust the variables as needed and repeat the last line as needed for the additional thumbnails.

    • This reply was modified 8 years ago by Curtis. Reason: Code typo

    oh good! ??

Viewing 14 replies - 1 through 14 (of 14 total)
  • The topic ‘Can this plugin auto import photos from my computer?’ is closed to new replies.