updater = $updater; } public function is_available() { return class_exists( 'WooCommerce' ); } public function optimize_product_images() { if ( ! $this->is_available() ) { return 0; } $updated = 0; $query = new WP_Query( array( 'post_type' => 'product', 'post_status' => array( 'publish', 'draft', 'pending', 'private' ), 'posts_per_page' => -1, 'fields' => 'ids', 'no_found_rows' => true, ) ); foreach ( $query->posts as $product_id ) { $product_id = absint( $product_id ); $product_name = sanitize_text_field( get_the_title( $product_id ) ); $thumb_id = absint( get_post_meta( $product_id, '_thumbnail_id', true ) ); if ( $thumb_id > 0 && $this->optimize_attachment_for_product( $thumb_id, $product_name ) ) { ++$updated; } $gallery_ids = (string) get_post_meta( $product_id, '_product_image_gallery', true ); if ( '' !== $gallery_ids ) { $ids = array_filter( array_map( 'absint', explode( ',', $gallery_ids ) ) ); foreach ( $ids as $image_id ) { if ( $image_id > 0 && $this->optimize_attachment_for_product( $image_id, $product_name ) ) { ++$updated; } } } } wp_reset_postdata(); return $updated; } protected function optimize_attachment_for_product( $attachment_id, $product_name ) { $current_alt = (string) get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ); $current_title = (string) get_the_title( $attachment_id ); $new_alt = '' === trim( $current_alt ) ? $product_name : $current_alt; $new_title = '' === trim( $current_title ) ? $product_name : $current_title; if ( $new_alt === $current_alt && $new_title === $current_title ) { return false; } return $this->updater->update_single( $attachment_id, $new_alt, $new_title ); } }