404 ] ); } $existing = self::find_existing_translation( $post_id, $target_lang ); if ( null !== $existing ) { return new WP_Error( 'adara_translation_exists', __( 'A translation already exists for this language.', 'adara-translate' ), [ 'status' => 409, 'translation_id' => $existing, 'edit_link' => get_edit_post_link( $existing, 'raw' ), ] ); } $title_result = Adara_Translate_Client::translate( $post->post_title, $target_lang, $source_lang ); if ( is_wp_error( $title_result ) ) { return $title_result; } $content_translated = Adara_Translate_Block_Translator::translate_content( $post->post_content, $target_lang, $source_lang ); if ( is_wp_error( $content_translated ) ) { return $content_translated; } $excerpt_translated = ''; if ( '' !== $post->post_excerpt ) { $excerpt_result = Adara_Translate_Client::translate( $post->post_excerpt, $target_lang, $source_lang ); if ( is_wp_error( $excerpt_result ) ) { return $excerpt_result; } $excerpt_translated = (string) $excerpt_result['translatedText']; } $new_post_id = wp_insert_post( [ 'post_title' => (string) $title_result['translatedText'], 'post_content' => (string) $content_translated, 'post_excerpt' => $excerpt_translated, 'post_status' => 'draft', 'post_type' => $post->post_type, 'post_author' => get_current_user_id(), ], true ); if ( is_wp_error( $new_post_id ) ) { return $new_post_id; } update_post_meta( (int) $new_post_id, self::META_LANGUAGE, sanitize_key( $target_lang ) ); update_post_meta( (int) $new_post_id, self::META_SOURCE_ID, $post_id ); return [ 'translation_id' => (int) $new_post_id, 'edit_link' => get_edit_post_link( $new_post_id, 'raw' ), 'language' => $target_lang, ]; } public static function find_existing_translation( int $source_id, string $target_lang ) : ?int { $query = new WP_Query( [ 'post_type' => 'any', 'post_status' => [ 'draft', 'pending', 'private', 'publish', 'future' ], 'posts_per_page' => 1, 'fields' => 'ids', 'no_found_rows' => true, 'meta_query' => [ 'relation' => 'AND', [ 'key' => self::META_SOURCE_ID, 'value' => $source_id ], [ 'key' => self::META_LANGUAGE, 'value' => sanitize_key( $target_lang ) ], ], ] ); $ids = $query->posts; return ! empty( $ids ) ? (int) $ids[0] : null; } }