query to create woocommerce products from images

I’d agree that doing this in SQL would be a lot more to learn than PHP. With WordPress functions you can run a query on all the images ( WP_Query ) and then loop through the results and use the info from the images to create a new post using [wp_insert_post()][2]. Finally you can update that post’s _thumbnail_id meta key ( [update_post_meta()][3], which stores the ID of the featured image.

Totally untested:

function wpa_convert_images_to_products(){

    $args = array(
    'post_type' => 'attachment', // Only bring back attachments
    'post_mime_type' => 'image', // Only bring back attachments that are images
    'posts_per_page' => '-1', // get them all
    'post_status' => 'inherit', // Attachments default to "inherit", rather than published. Use "inherit" or "all".
    );

    $images = new WP_Query( $args );


    if ( $images->have_posts() ) while( $images->have_posts() ) {

        $images->the_post();

        $post = array(
            'post_title' => get_the_title(),
            'post_excerpt' => get_the_excerpt(),
            'post_type' => 'product',
        );
        $post_id = wp_insert_post( $post );

        update_post_meta( $post_id, '_thumbnail_id', get_the_ID() );
    }


}

add_action('admin_init', 'wpa_convert_images_to_products' );

You would only want to run this ONCE, or you will get a small ton of new products.

Editing to add that you can ensure that this only runs one time with the use of a transient.

function wpa_convert_images_to_products(){

  if ( false === get_transient( 'wpa_convert_images_to_products' ) ) ) {

    $args = array(
      'post_type' => 'attachment', // Only bring back attachments
      'post_mime_type' => 'image', // Only bring back attachments that are images
      'posts_per_page' => '-1', // get them all
      'post_status' => 'inherit', // Attachments default to "inherit", rather than published. Use "inherit" or "all".
     );

    $images = new WP_Query( $args );

    if ( $images->have_posts() ) {

      while( $images->have_posts() ) {

        $images->the_post();

        $post = array(
          'post_title' => get_the_title(),
          'post_excerpt' => get_the_excerpt(),
          'post_type' => 'product',
        );
        $post_id = wp_insert_post( $post );

        update_post_meta( $post_id, '_thumbnail_id', get_the_ID() );

      }

      set_transient( 'wpa_convert_images_to_products', $images );

    }

}
add_action( 'admin_init', 'wpa_convert_images_to_products' );

Leave a Comment