Productafbeeldingen toevoegen (Script, PHP-API)
Hoe kun je in bulk productafbeeldingen importeren en associëren met producten? Zo dus... Let op: Het eigenlijke script vind je aan het eind van dit artikel.
Uitgangspunt
- Site, afbeeldingen & dwh bevinden zich op dezelfde computer: M'n laptop, die tevens m'n ontwikkelomgeving is
- Afbeeldingen bevinden zich in een map op m'n laptop: Eén afbeelding per product per taal. Deze map kan ook de bestaande WordPress-upload-map zijn. Het zou handig zijn als het in ieder geval geen externe URL is, ivm. performance als het (in de toekomst) om duizenden afbeeldingen gaat. Een locale URL is geen probleem
- In het dwh zit een tabel met de namen van deze afbeeldingen, met daaraan gekoppeld de meta-data voor deze afbeeldingen.
Beoogde resultaat
- Afbeeldingen worden geïncorporeerd in de site (sideloading?)
- Meta-data wordt gekoppeld aan deze afbeeldingen (bestandsnaam is primaire sleutel).
Bulk-import van afbeeldingen
- LET OP:
media_sideload_image
associëert uploads alleen met een post, als de gebruiker dat aangeeft! Deze functionaliteit is optioneel. Het staat er echt: https://developer.wordpress.org/reference/functions/media_sideload_image/
- Desalniettemin: Dit script is verrekte traag: Zo'n 16h voor 32.000 afbeeldingen op m'n laptop.
Producten & Thumbnail
Met product image, featured image of thumbnail, wordt hier de 'primaire productfoto' bedoeld. Misschien dat deze spraakverwarring een deel van het probleem is - Dat ik verschillende concepten door elkaar haal - Wordt vervolgd.
Setting the stage
Add product image
Producten & Gallery
Naast de thumbnail heb je per product de mogelijkheid om additionele afbeeldingen toe te voegen aan de zogenaamde gallery.
Gebruik update_post_meta
om in wp_postmeta
te schrijven
[1] Gebruikt deze code om een gallery-image toe te voegen. Dit werkt echter niet als je meerdere gallery-images wilt toevoegen:
########################################################## # optionally add second image ########################################################## # require_once(ABSPATH . “wp-admin” . ‘/includes/image.php’); $thumb_url2 = “http://sportsweatherstats.com/pics/NFLpredict.png”; # Download file to temp location ################################ # $tmp2 = download_url( $thumb_url2 ); $logtxt .= “download_url2: $tmp2\n”; # fix file name for query strings ################################# # preg_match(‘/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/’, $thumb_url2, $matches); $file_array2[‘name’] = basename($matches[0]); $file_array2[‘tmp_name’] = $tmp2; $imgID = media_handle_sideload( $file_array2, $new_post_id, ‘desc’ ); $logtxt .= “ThumbID2: $imgID\n”; # Update wp_postmeta ############################# # update_post_meta( $new_post_id, ‘_product_image_gallery’, $imgID);
Producten & afbeeldingen - Meertalig
Voor meertalige producten met een eigen afbeelding per taal (ivm. aangepaste titels, alt-tekst, etc.) zijn er een paar bijzonderheden:
- WordPress » Languages » Media (activate languages and translations for media): Activeren. Nu heb je per taal een aparte media library. Dat zie je, als je de afbeeldingen weergeeft in grid. Als je ze weergeeft in een lijst, zie je dit niet zo snel
- Voor alle afbeeldingen moet de taal zijn gespecificeerd
- Taalvarianten van producten moeten met elkaar gekoppeld zijn middels
pll_save_post_translation
- Taalvarianten van afbeeldingen moeten ook met elkaar gekoppeld zijn middels
pll_save_post_translation
- Pas nú kun je afbeeldingen en producten koppelen middels
set_post_thumbnail
.
Verder worden gekoppelde producten qua afbeelding op een bepaalde manier als één product beschouwd:
- Als je de afbeelding verwijdert in 1 taalvariant van een product, worden de afbeeldingen bij de andere taalvarianten van dat product, ook verwijderd!
- Als de koppeling hierboven niet goed is gegaan, zie je bij alle gekoppelde producten, dezelfde afbeelding, meestal de laatste afbeelding die je hebt toegekend. Als je niet weet hoet dit ziet met gekoppelde producten, kan dat héél verrassend overkomen!
Afbeeldingen in bulk verwijderen
Script: Afbeeldingen uploaden + associeren met posts + taal
Dit script doet zo'n beetje alles wat in de artikel is behandeld:
<?php # # Upload products & images from dwh + connect translations ############################################################### # echo "\n\n"; echo "###############################################################\n"; echo "###############################################################\n"; echo "###############################################################\n"; ############################################################### # Libraries ############################################################### # $pad = "/home/strompf/www/rt.dvb/"; require_once($pad . "wp-load.php"); require_once($pad . 'wp-admin/includes/media.php'); require_once($pad . 'wp-admin/includes/file.php'); require_once($pad . 'wp-admin/includes/image.php'); ############################################################### # Set variables ############################################################### # # This is the export table in the dwh. It contains per row all # relevant product & image data # $product_table_name = "20190506_2010_product_exp"; ############################################################### # Main ############################################################### # # Delete previous content ######################### # dvb_delete_all_products(); # Defined in functions.php dvb_delete_all_thumbnails(); # Defined in functions.php # Connect with dwh ################## # $conn = create_pdo_object(); # Fetch product_table from dwh ############################## # $rows = fetch_product_rows($conn, $product_table_name); # Post all products, get $product_and_images array ################################################## # # Structure of $products array - Example # # Array # ( # [0] => Array # ( # [post_id] => 1360 # [lang] => nl # Can be used for both products & images - They're always the same language # [sku] => bellow_01 # [image_file_name] => xxx # [image_title] => xxx # [image_alt] => xxx # [image_caption] => xxx # [image_description] => xxx # [image_id] => 2567 # ) # $products_and_images = post_all_products($rows); // echo "\n\n### $products_and_images (1):\n"; // print_r($products_and_images); # Connect product translations ############################## # connect_product_translations($products_and_images); # Upload images & connect products with images ############################################## # $products_and_images = upload_images($products_and_images); // echo "\n\n### $products_and_images - Na upload_and_connect_images:\n"; // print_r($products_and_images); # Connect image translations ############################################### # connect_image_translations($products_and_images); # Set thumbnails ############################################### # set_thumbnails($products_and_images); ############################################################### # Set thumbnails ############################################################### # function set_thumbnails($products_and_images) { foreach ($products_and_images as $key => $row) { # Set thumbnail ############### # # echo "Set thumbnail: product_id: ".$row['post_id']."\n"; # echo "Set thumbnail: image_id: ".$row['image_id']."\n"; # set_post_thumbnail($row['post_id'], $row['image_id']); } } ############################################################### # Upload images ############################################################### # # All info is available in $products_and_images! # function upload_images($products_and_images) { echo "\n### Function upload_images...\n"; # Set vars ########## # $pad="http://rt.dvb/wp-content/uploads/tmp/"; $return="id"; foreach ($products_and_images as $key => $row) { # Fetch data ####################################################### # # When $image_id contains something like a "page not # found"-error, it means that the image wasn't found # $product_id = $row['post_id']; $image_file_name = $pad . $row['image_file_name']; $image_title = $row['image_title']; $image_alt = $row['image_alt']; $image_caption = $row['image_caption']; $image_description = $row['image_description']; $image_lang = $row['lang']; # Debug ####### # // echo "\n\n### New row...\n"; // echo "row-array:\n"; // print_r($row); // echo "\n"; // echo "product_id: ".$row['post_id']."\n"; // echo "post_title: ".$row['post_title']."\n"; // echo "image_file_name: ".$image_file_name."\n"; # echo "sku: ".$row['sku']."\n"; # Upload image ############## # $image_id = media_sideload_image($image_file_name, $product_id, $image_description, $return); # Store $image_id in $products_and_images ########################################## # $products_and_images[$key]['image_id'] = $image_id; # print_r($row); # Set language ########################################## # pll_set_post_language($image_id, $row['lang']); # Debug ####### # # echo "media_sideload_image: Returned image_id:".$image_id."\n"; # print_r($image_id); # Set image properties ################################ # # These are not meta-fields, but columns in wp_posts # $update_post = array ( 'ID' => $image_id, 'post_title' => $image_title, 'post_excerpt' => $image_caption, 'post_content' => $image_description ); wp_update_post($update_post); # Set Alt-text ################################ # # This happens to be the only meta-field that is used for images # (they don't use much meta-fields anyway) # update_post_meta($image_id, "_wp_attachment_image_alt", $image_alt); } # Return $products_and_images #################################### # # Augmented with $image_id # return $products_and_images; } ############################################################### # Connect image translations ############################################################### # function connect_image_translations($products_and_images) { # Cycle through all rows ######################## # foreach ($products_and_images as $row) { # Get elements ####################### # $sku1 = $row['sku']; $post_id1 = $row['image_id']; $lang1 = $row['lang']; # Set first array item ###################### # $tuple = array ( $lang1 => $post_id1 ); # Loop through all other items ############################## # foreach ($products_and_images as $row2) { # Get elements ############## # $sku2 = $row2['sku']; $post_id2 = $row2['image_id']; $lang2 = $row2['lang']; # Copy when matching ######################### # if ($sku1==$sku2 and $lang1<>$lang2) { $tuple=$tuple + array ( $lang2 => $post_id2 ); } } # Debugging: Display resulting array #################################### # echo "\n\n### Connect image translations for sku ".$sku1.":\n"; print_r($tuple); # Post to site! ######################### # pll_save_post_translations($tuple); } } ############################################################### # Connect product translations ############################################################### # function connect_product_translations($products_and_images) { # Cycle through all rows ######################## # foreach ($products_and_images as $row) { # Get elements ####################### # $sku1 = $row['sku']; $post_id1 = $row['post_id']; $lang1 = $row['lang']; # Set first array item ###################### # $tuple = array ( $lang1 => $post_id1 ); # Loop through all other items ############################## # foreach ($products_and_images as $row2) { # Get elements ############## # $sku2 = $row2['sku']; $post_id2 = $row2['post_id']; $lang2 = $row2['lang']; # Copy when matching ######################### # if ($sku1==$sku2 and $lang1<>$lang2) { $tuple=$tuple + array ( $lang2 => $post_id2 ); } } # Debugging: Display resulting array #################################### # // echo "\n\n### Connect product translations for sku ".$sku1.":\n"; // print_r($tuple); # Post to site! ######################### # pll_save_post_translations($tuple); } } ############################################################### # Post all products ############################################################### # function post_all_products($rows) { foreach ($rows as $row) { $array=process_product_row($row, $array); } return $array; } ############################################################### # Function: process_product_row($row) ############################################################### # function process_product_row($row, $array) { $product_array=array ( 'post_title' => $row['post_title'], 'post_content' => $row['post_content'], 'post_excerpt' => $row['post_excerpt'], 'post_status' => 'publish', 'post_type' => 'product' ); # Create post ########################################## # $post_id = wp_insert_post($product_array); # Designate kind of product ########################################## # wp_set_object_terms($post_id, 'simple', 'product_type'); # Meta fields ########################################## # update_post_meta($post_id, '_sku', $row['_sku']); update_post_meta($post_id, '_regular_price', $row['_regular_price']); update_post_meta($post_id, '_price', $row['_price']); update_post_meta($post_id, '_downloadable', 'no' ); update_post_meta($post_id, '_virtual', 'no' ); update_post_meta($post_id, '_manage_stock', 'no' ); update_post_meta($post_id, '_sold_individually', 'yes' ); update_post_meta($post_id, '_yoast_wpseo_metadesc', $row['post_meta_description']); update_post_meta($post_id, '_yoast_wpseo_focuskw', $row['post_focuskw']); # Language ########################################## # pll_set_post_language($post_id, $row['lang']); # $products_and_images-Array: Created or updated HERE! ###################################################### # if (empty($array)) { # Create array - This array is used as the main dataobject # throughout this script # $array = array ( 0 => array ( post_id => $post_id, lang => $row['lang'], sku => $row['_sku'], image_file_name => $row['image_file_name'], image_title => $row['image_title'], image_alt => $row['image_alt'], image_caption => $row['image_caption'], image_description => $row['image_description'], image_id => 0 # Misschien hoef je dit veld niet vantevoren te declareren ) ); } else { $temp = array ( post_id => $post_id, lang => $row['lang'], sku => $row['_sku'], image_file_name => $row['image_file_name'], image_title => $row['image_title'], image_alt => $row['image_alt'], image_caption => $row['image_caption'], image_description => $row['image_description'] ); array_push($array,$temp); } return $array; } ############################################################### # Function: fetch_product_rows ############################################################### # function fetch_product_rows($conn, $table_name) { # Formulate query ################################################### # $sql = $conn->prepare("select * from ".$table_name); # Execute query ############### # $sql->execute(); # Fetch rows ############ # return $sql->fetchAll(); } ############################################################### # Function: create_pdo_object ############################################################### # function create_pdo_object() { ############################################################### # Connect with dwh through PDO ############################################################### # $servername = "localhost"; $dbname = "xxx"; $username = "xxx"; $password = "xxx"; try { # Instantiate a new PDO object ############################## # $conn = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8", $username, $password); # set the PDO error mode to exception ##################################### # $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); # echo "Connected successfully\n"; } catch(PDOException $e) { echo "PDO Connection failed: " . $e->getMessage()."\n"; } return $conn; }
Zie ook
- Afbeeldingen & databasemodel (WordPress)
- Afbeeldingen & WP-CLI
- Automatisering (WordPress)
- Db.bulk (WordPress)
- PHP-API (WordPress)
Bronnen
- http://www.wpallimport.com/documentation/images/meta-data/
- https://developer.wordpress.org/cli/commands/media/import/
- http://jafty.com/blog/tag/use-php-to-add-images-to-woocommerce-product/ - Heel interessant voorbeeld, hoe producten + afbeeldingen + koppeling in PHP wordt gedaan
- https://stackoverflow.com/questions/36947042/woocommerce-change-product-image-via-php
- https://stackoverflow.com/questions/32837968/how-to-get-featured-image-of-a-product-in-woocommerce
- https://gist.github.com/zarankumar/f80a73598152edf7d67a8c91dbf3be25
- https://wordpress.stackexchange.com/questions/40301/how-do-i-set-a-featured-image-thumbnail-by-image-url-when-using-wp-insert-post/41300
- https://stackoverflow.com/questions/15044173/update-post-meta-to-add-featured-image-to-post-no-longer-works-after-update-to-w
- https://codex.wordpress.org/Function_Reference/get_attached_media
- https://codex.wordpress.org/Function_Reference/update_post_meta
- https://wordpress.stackexchange.com/questions/50123/image-upload-from-url
- https://wordpress.stackexchange.com/questions/100838/how-to-set-featured-image-to-custom-post-from-outside-programmatically
- https://www.google.nl/search?q=media_sideload_image+not+being+attached+to+woocommerce+product
- https://wordpress.stackexchange.com/questions/2888/can-i-refresh-the-thumbnails-programmatically - wp_update_attachment_metadata?