Last active
April 3, 2018 13:07
-
-
Save robertdevore/9803c06086d27be2abbd540ad925cf62 to your computer and use it in GitHub Desktop.
WooCommerce Set Featured Images function
This file contains 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 | |
// Get attachment ID from the file URL. | |
function sandbox_get_image_id( $image_url ) { | |
global $wpdb; | |
$attachment = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url ) ); | |
return $attachment[0]; | |
} | |
/** | |
* FUNCTION: sandbox_wc_image | |
* Set WooCommerce Featured Image | |
*/ | |
function sandbox_set_wc_image() { | |
// Get the total product count. | |
$args = array( 'post_type' => 'product', 'post_status' => 'publish', 'posts_per_page' => -1 ); | |
$products = new WP_Query( $args ); | |
$count = $products->found_posts; | |
global $post; | |
// Get the products. | |
$getproducts = array( | |
'post_type' => 'product', | |
'post_status' => 'publish', | |
'ignore_sticky_posts' => 1, | |
'posts_per_page' => $count, | |
); | |
$allproducts = new WP_Query( $getproducts ); | |
$allproducts = $allproducts->get_posts(); | |
// Loop through each product. | |
foreach( $allproducts as $product ) { | |
// Get the first image. | |
$images = get_posts( | |
array( | |
'post_type' => 'attachment', | |
'post_mime_type' => 'image', | |
'post_parent' => $product->ID, // the ID foreach | |
'posts_per_page' => 1, | |
) | |
); | |
$content = $product->post_content; | |
$first_img = ''; | |
ob_start(); | |
ob_end_clean(); | |
$first_img = preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches ); | |
if( empty( $first_img ) ) { | |
$first_img = ''; | |
} else { | |
$first_img = $matches[1][0]; | |
} | |
// Set the featured image. | |
if ( $images ) { | |
foreach( $images as $image ) { | |
if ( $image->ID !== '' ) { | |
// set the featured image for this post here. | |
set_post_thumbnail( $product->ID, $image->ID ); | |
} | |
} | |
} else { | |
$firstimg = $first_img; | |
$image_id = sandbox_get_image_id( $firstimg ); | |
// set the featured image for this post here. | |
set_post_thumbnail( $product->ID, $image_id ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment