Non-empty translatable values: field => text. */ public function collect( int $post_id ): array { $out = array(); foreach ( $this->fields->translatable() as $field ) { $text = $this->fields->read( $post_id, $field ); if ( '' !== trim( $text ) ) { $out[ $field ] = $text; } } return $out; } /** * The source post's SEO texts in $to. Nothing is saved. * * @return array|WP_Error field => translated text. */ public function translate_values( int $source_id, string $to, ?Provider $provider = null ): array|WP_Error { $values = $this->collect( $source_id ); if ( ! $values ) { return array(); } $from = $this->posts->language_of( $source_id ); if ( $from === $to ) { return new WP_Error( 'blocklingo_same_lang', __( 'Source and target are in the same language.', 'blocklingo' ) ); } $post = get_post( $source_id ); $type = $post ? get_post_type_object( $post->post_type ) : null; $hints = array(); foreach ( array_keys( $values ) as $field ) { $hints[ $field ] = SeoFields::hint( $field ); } $summary = $post ? ( $post->post_excerpt ? $post->post_excerpt : wp_trim_words( $post->post_content, 120 ) ) : ''; $result = $this->translator->translate_strings( $values, array_fill_keys( array_keys( $values ), 'text' ), $from, $to, $provider, array( 'hints' => $hints, 'context' => array( 'title' => $post ? $post->post_title : '', 'type' => $type ? (string) $type->labels->singular_name : '', 'outline' => $post ? $post->post_title . "\n" . wp_strip_all_tags( strip_shortcodes( $summary ) ) : '', ), ) ); return is_wp_error( $result ) ? $result : array_map( 'strval', $result ); } /** * Save field => text values on a post, without triggering sync. * * @param array $values */ public function apply( int $post_id, array $values ): void { $this->sync->paused( function () use ( $post_id, $values ): void { foreach ( $values as $field => $text ) { $this->fields->write( $post_id, (string) $field, (string) $text ); } } ); } /** * Translate the source's SEO texts into the target post's language and save them. * * @return array|WP_Error */ public function translate( int $source_id, int $target_id, ?Provider $provider = null ): array|WP_Error { $values = $this->translate_values( $source_id, $this->posts->language_of( $target_id ), $provider ); if ( ! is_wp_error( $values ) ) { $this->apply( $target_id, $values ); } return $values; } /** Remove canonical-style fields from a freshly copied translation. */ public function clear_per_language( int $post_id ): void { foreach ( $this->fields->per_language() as $field ) { $this->fields->remove( $post_id, $field ); } } }