Loop through All WooCommerce Products and Check if They Have an Image or Attribute

Create a file called page-test.php in your theme folder and a page called Test in WordPress. Put this code in your page-test.php file, and you’re good to go!

<?php

add_action( 'genesis_meta', 'enterprise_home_genesis_meta' );


function create_table($data) {
  $table_string = '';
  $table_string .= '<table>';
  $table_string .= '<tr>';
  $table_string .= '<td>Title</td>';
  $table_string .= '<td>SKU</td>';
  $table_string .= '<td>ID</td>';
  $table_string .= '</tr>';

  foreach ($data as $product) {
    $table_string .= '<tr>';
    $table_string .=  '<td>' . $product['title'] . '</td>';
    $table_string .=  '<td>' . $product['sku'] . '</td>';
    $table_string .=  '<td>' . $product['id'] . '</td>';
    $table_string .= '</tr>';
  }

  $table_string .= '</table>';

  return $table_string;
}


// ********* Get all products and variations and sort alphbetically, return in array (title, sku, id)*******
function get_woocommerce_product_list() {
  $full_product_list = array();

  $loop = new WP_Query( array( 'post_type' => array('product'), 'posts_per_page' => -1 ) );
 
  while ( $loop->have_posts() ) : $loop->the_post();

    $theid = get_the_ID();
    $product = new WC_Product($theid);

    // $product_code is an attribute of the product
    $product_code = $product->get_attribute('pa_new-product-code');
    // use this if statement to record a list of products that don't have images
    //if (!has_post_thumbnail($theid)) {
    // use this if statement to record a list of products that don't have a certain attribute
    if (!$product_code) {

      $sku = get_post_meta($theid, '_sku', true );
      $thetitle = get_the_title();
      // add product to array
      if (!empty($sku)) {
        $full_product_list[] = array(
          'title' => $thetitle, 
          'sku' => $sku, 
          'id' => $theid
        );
      }
    }

  endwhile; wp_reset_query();

  // sort into alphabetical order, by title
  sort($full_product_list);

  $product_table = create_table($full_product_list);

  $no_match_file = get_stylesheet_directory();
  $no_match_file .= '/no_woo_image.log';
  // echo the array onto the screen
  echo '<pre>';
  var_dump($product_table);
  var_dump($full_product_list);
  echo '</pre>';
  // use file_put_contents to dump the array into a file in your theme
  //file_put_contents($no_match_file, print_r($full_product_list, true));
}
get_woocommerce_product_list();

genesis();