Last active
January 19, 2018 13:41
-
-
Save EricBusch/c91dfccdd2da10b568c55a3314e87b15 to your computer and use it in GitHub Desktop.
Imports additional product images for an array of given fields as gallery images for a WooCommerce product. [datafeedr][dfrps][dfrpswc]
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
<?php | |
/** | |
* Imports additional product images for an array of given fields as gallery images | |
* for a WooCommerce product. | |
* | |
* @param WP_Post $post | |
*/ | |
function mycode_import_woocommerce_gallery_images( $post ) { | |
/** | |
* Modify this array and add the product fields that have alternate images | |
* that you want to be imported into a product's gallery. | |
*/ | |
$image_fields = array( | |
'alternateimage', | |
'alternateimagetwo', | |
'alternateimagethree', | |
'alternateimagefour', | |
); | |
// Stop editing here. | |
if ( 'publish' != $post->post_status ) { | |
return; | |
} | |
$product = dfrps_product( $post->ID ); | |
if ( empty( $product ) ) { | |
return; | |
} | |
$urls = []; | |
foreach ( $image_fields as $image_field ) { | |
if ( ! isset( $product[ $image_field ] ) ) { | |
continue; | |
} | |
if ( ! dfrapi_string_starts_with( $product[ $image_field ], [ 'http', '//' ] ) ) { | |
continue; | |
} | |
$urls[ $image_field ] = $product[ $image_field ]; | |
} | |
if ( empty( $urls ) ) { | |
return; | |
} | |
$args = array( | |
'title' => $post->post_title, | |
'file_name' => $post->post_title, | |
'post_id' => $post->ID, | |
'description' => $post->post_content, | |
'caption' => $post->post_title, | |
'alt_text' => $post->post_title, | |
'user_id' => $post->post_author, | |
'is_post_thumbnail' => false, | |
'timeout' => 20, | |
); | |
$gallery_meta_key = '_product_image_gallery'; | |
$gallery_ids = get_post_meta( $post->ID, $gallery_meta_key, true ); | |
$gallery_ids = array_filter( explode( ',', $gallery_ids ) ); | |
$update_gallery_ids = false; | |
foreach ( $urls as $field => $url ) { | |
$image_check_meta_key = '_mycode_product_image_gallery_' . $field; | |
if ( dfrps_image_import_attempted( $post->ID, $image_check_meta_key ) ) { | |
continue; | |
} | |
$result = datafeedr_import_image( $url, $args ); | |
update_post_meta( $post->ID, $image_check_meta_key, 0 ); | |
if ( is_wp_error( $result ) || $result->has_error() ) { | |
continue; | |
} | |
$gallery_ids[] = $result->attachment_id(); | |
$update_gallery_ids = true; | |
} | |
if ( $update_gallery_ids ) { | |
update_post_meta( $post->ID, $gallery_meta_key, implode( ',', $gallery_ids ) ); | |
} | |
} | |
add_action( 'the_post', 'mycode_import_woocommerce_gallery_images' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment