Last active
September 15, 2017 17:12
-
-
Save ScottGarrison/540a0ddbe047c000e94f0a1d03c974a0 to your computer and use it in GitHub Desktop.
Specific use case wordpress image upload hook. Used to match image file names with csv file row values. Also uses WP Real Media Library to move files into specific sections depending on the image
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function ph_image_upload_modification( $attachment_ID ) { | |
| // set up file name | |
| $filename = $_REQUEST['name']; | |
| $withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $filename); | |
| $withoutExt = str_replace(array('-','_'), ' ', $withoutExt); | |
| // set line endings for csv file | |
| ini_set('auto_detect_line_endings',TRUE); | |
| // function handling getting csv file | |
| function readCSV($csvFile){ | |
| $file_handle = fopen($csvFile, 'r'); | |
| while (!feof($file_handle) ) { | |
| $line_of_text[] = fgetcsv($file_handle, 0); | |
| } | |
| fclose($file_handle); | |
| return $line_of_text; | |
| } | |
| // get csv file | |
| $csv = readCSV(ABSPATH . 'product_image_assoc.csv'); // Make sure this exsists or you will have a forever error log. | |
| // go through csv file rows | |
| foreach ( $csv as $key => $c ) { | |
| $firstColumn = $c[0]; | |
| $secondColumn = $c[1]; | |
| // if it matches a column, attach the description and break loop | |
| if ($firstColumn === $withoutExt) { | |
| $my_post = array( | |
| 'ID' => $attachment_ID, | |
| 'post_excerpt' => $withoutExt, // caption | |
| 'post_content' => $secondColumn, // description | |
| ); | |
| wp_update_post( $my_post ); | |
| $moved = wp_rml_move(1, array($attachment_ID)); | |
| break; | |
| } | |
| // if it's the last row and it doesn't match this one, put in a secondary folder for manual proces | |
| end($csv); | |
| if ($key === key($csv) && $firstColumn !== $withoutExt) { | |
| $moved = wp_rml_move(2, array($attachment_ID)); | |
| } | |
| } | |
| } | |
| add_filter( 'add_attachment', 'ph_image_upload_modification', 99999, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment