__( 'Insufficient permissions.', 'ahs-image-to-webp-converter' ) ) ); } $batch = isset( $_POST['batch'] ) ? absint( $_POST['batch'] ) : 0; $result = $this->process_batch( $batch ); wp_send_json_success( $result ); } /** * Process a single batch of images. * * @param int $batch Current batch number. * @return array */ private function process_batch( $batch ) { // Note: We always grab the next set of images that haven't been converted. $images = $this->get_unconverted_image_ids( 0, self::BATCH_SIZE ); $results = array( 'converted' => 0, 'failed' => 0, 'skipped' => 0, 'logs' => array() ); if ( empty( $images ) ) { $results['total'] = $this->get_total_unconverted_count(); $results['has_more'] = false; return $results; } $converter = new AHSITW_Converter(); foreach ( $images as $image_id ) { // Limit check before processing each image. if ( ! AHSITW_Limiter::can_convert() ) { $results['logs'][] = array( 'message' => __( 'Conversion limit reached. Please upgrade to continue.', 'ahs-image-to-webp-converter' ), 'type' => 'error' ); break; } // Use the centralized method to convert and update the attachment. if ( $converter->update_attachment_to_webp( $image_id ) ) { $results['converted']++; AHSITW_Limiter::increment(); } else { $results['failed']++; } } $total = $this->get_total_unconverted_count(); $results['total'] = $total; $results['has_more'] = $total > 0; return $results; } /** * Get IDs of images that haven't been converted to WebP. * * @param int $offset (unused now for efficiency) * @param int $limit * @return array */ private function get_unconverted_image_ids( $offset, $limit ) { $args = array( 'post_type' => 'attachment', 'post_mime_type' => array( 'image/jpeg', 'image/png' ), 'post_status' => 'inherit', 'posts_per_page' => $limit, 'fields' => 'ids', 'meta_query' => array( array( 'key' => '_AHSITW_converted', 'compare' => 'NOT EXISTS', ), ), 'no_found_rows' => true, ); $query = new WP_Query( $args ); return $query->posts; } /** * Get total count of unconverted images (cached). * * @return int */ public function get_total_unconverted_count() { $args = array( 'post_type' => 'attachment', 'post_mime_type' => array( 'image/jpeg', 'image/png' ), 'post_status' => 'inherit', 'posts_per_page' => 1, 'fields' => 'ids', 'meta_query' => array( array( 'key' => '_AHSITW_converted', 'compare' => 'NOT EXISTS', ), ), 'no_found_rows' => false, // We need the total count. ); $query = new WP_Query( $args ); return absint( $query->found_posts ); } /** * Static helper to get total count. * * @return int */ public static function get_convertible_count() { $instance = new self(); return $instance->get_total_unconverted_count(); } }