' . esc_html__( 'AI Multisite Translate requires WordPress 7.0 or higher.', 'ai-multisite-translate' ) . '
';
} );
return;
}
add_action( 'enqueue_block_editor_assets', [ $this, 'enqueue_gutenberg_button' ] );
add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_classic_editor_button' ] );
add_action( 'edit_form_after_title', [ $this, 'classic_editor_button' ] );
add_action( 'wp_ajax_aimstr_generate_translations', [ $this, 'ajax_generate_translations' ] );
add_action( 'wp_ajax_aimstr_get_site_posts', [ $this, 'ajax_get_site_posts' ] );
add_action( 'wp_ajax_aimstr_translate_post', [ $this, 'ajax_translate_post' ] );
add_filter( 'network_admin_plugin_action_links_' . plugin_basename( __FILE__ ), [ $this, 'add_plugin_action_links' ] );
add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), [ $this, 'add_plugin_action_links' ] );
}
public function add_plugin_action_links( $links ) {
$settings_link = sprintf(
'%s',
esc_url( network_admin_url( 'admin.php?page=aimstr-network' ) ),
esc_html__( 'Settings', 'ai-multisite-translate' )
);
array_unshift( $links, $settings_link );
return $links;
}
/**
* Get the current site ID and post ID.
*/
private function get_this_page_and_blog_id() {
return [
'site_id' => get_current_blog_id(),
'page_id' => get_the_ID(),
];
}
/**
* Get all network sites with their languages, excluding the current site.
*/
private function get_all_site_language_list() {
$current_site_id = get_current_blog_id();
$sites = array_filter(
array_map( function( $site ) {
return [
'site_id' => (int) $site->blog_id,
'language' => get_blog_option( $site->blog_id, 'WPLANG', '' ) ?: 'en_US',
];
}, get_sites() ),
function( $site ) use ( $current_site_id ) {
return $site['site_id'] !== $current_site_id;
}
);
return array_values( $sites );
}
/**
* Fetch the translatable data from a post.
*/
private function fetch_all_translatable_data( $post_id ) {
$post = get_post( $post_id );
if ( ! $post ) {
return null;
}
$data = [
'title' => $post->post_title,
'content' => $post->post_content,
'post_type' => $post->post_type,
'post_status' => $post->post_status,
];
/**
* Filter to allow additional translatable data to be added.
*
* @param array $data The translatable data.
* @param int $post_id The post ID.
*/
return apply_filters( 'aimstr_translatable_data', $data, $post_id );
}
/**
* Translate a string to a given language using the AI client.
*/
private function translate_string( $text, $language, $context = 'content' ) {
if ( $context === 'title' ) {
$prompt = "Translate the following title to {$language}. Return only the translated title, nothing else.\n\n{$text}";
} else {
$prompt = "Translate the following text to {$language}. Return only the translated text, nothing else. Do not add any commentary or ask for clarification -- even if the text is short, simply translate it.\n\n{$text}";
}
$result = wp_ai_client_prompt( $prompt )
->using_abilities( [ 'text_generation' ] )
->generate_text();
return is_wp_error( $result ) ? null : $result;
}
/**
* Log a debug message if WP_DEBUG_LOG is enabled.
*/
private function log( string $message ): void {
if ( defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
error_log( 'AIMSTR: ' . $message ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
}
}
/**
* Get or create a translation group UUID for a post.
*/
private function get_or_create_group_id( int $site_id, int $post_id ): string {
switch_to_blog( $site_id );
$group_id = get_post_meta( $post_id, '_aimstr_translation_group', true );
restore_current_blog();
return $group_id ?: wp_generate_uuid4();
}
/**
* AJAX handler to generate translations for all network sites.
*/
public function ajax_generate_translations() {
check_ajax_referer( 'aimstr_generate', 'nonce' );
if ( ! current_user_can( 'edit_posts' ) ) {
wp_send_json_error( 'Insufficient permissions.' );
}
$post_id = isset( $_POST['post_id'] ) ? (int) $_POST['post_id'] : 0;
$source_data = $this->fetch_all_translatable_data( $post_id );
if ( ! $source_data ) {
wp_send_json_error( 'Invalid post.' );
}
$sites = $this->get_all_site_language_list();
if ( empty( $sites ) ) {
wp_send_json_error( 'No other sites found in the network.' );
}
$group_id = $this->get_or_create_group_id( get_current_blog_id(), $post_id );
update_post_meta( $post_id, '_aimstr_translation_group', $group_id );
update_post_meta( $post_id, '_aimstr_is_source', true );
update_post_meta( $post_id, '_aimstr_source_site', get_current_blog_id() );
update_post_meta( $post_id, '_aimstr_source_post', $post_id );
$results = [];
foreach ( $sites as $site ) {
$language = $site['language'];
$site_id = $site['site_id'];
$translated_title = $this->translate_string( $source_data['title'], $language, 'title' );
$translated_content = $this->translate_string( $source_data['content'], $language, 'content' );
if ( ! $translated_title || ! $translated_content ) {
$results[] = "Site {$site_id}: translation failed.";
continue;
}
$extra_fields = $source_data['extra_fields'] ?? [];
$translated_extra_fields = [];
foreach ( $extra_fields as $key => $value ) {
$translated_extra_fields[ $key ] = $this->translate_string( $value, $language, 'content' );
}
switch_to_blog( $site_id );
// Check if a translated version already exists for this group
$existing = get_posts([
'post_type' => $source_data['post_type'],
'post_status' => 'any',
'meta_key' => '_aimstr_translation_group',
'meta_value' => $group_id,
'numberposts' => 1,
'fields' => 'ids',
]);
if ( $existing ) {
$new_post_id = $existing[0];
wp_update_post([
'ID' => $new_post_id,
'post_title' => $translated_title,
'post_content' => $translated_content,
'post_status' => $source_data['post_status'],
]);
} else {
$new_post_id = wp_insert_post([
'post_title' => $translated_title,
'post_content' => $translated_content,
'post_status' => $source_data['post_status'],
'post_type' => $source_data['post_type'],
]);
}
update_post_meta( $new_post_id, '_aimstr_translation_group', $group_id );
update_post_meta( $new_post_id, '_aimstr_source_site', get_current_blog_id() );
update_post_meta( $new_post_id, '_aimstr_source_post', $post_id );
do_action( 'aimstr_after_post_inserted', $new_post_id, $translated_extra_fields, $site );
restore_current_blog();
$results[] = "Site {$site_id} ({$language}): translation completed.";
}
wp_send_json_success( implode( ', ', $results ) );
}
/**
* Render the Generate Translations button in the classic editor.
*/
public function classic_editor_button($post)
{
if (use_block_editor_for_post($post)) {
return;
}
?>
admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'aimstr_generate' ),
] );
}
/**
* Enqueue scripts for the classic editor.
*/
public function enqueue_classic_editor_button($hook)
{
if (!in_array($hook, ['post.php', 'post-new.php'], true)) {
return;
}
wp_enqueue_script('jquery');
wp_localize_script('jquery', 'aimstrData', [
'ajaxUrl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('aimstr_generate'),
'textGenerating' => __('Generating...', 'ai-multisite-translate'),
'textDone' => __('Done!', 'ai-multisite-translate'),
]);
wp_add_inline_script('jquery', '
function aimstrGenerate(postId) {
var status = document.getElementById("aimstr-status");
if (status) status.innerText = aimstrData.textGenerating;
jQuery.post(aimstrData.ajaxUrl, {
action: "aimstr_generate_translations",
nonce: aimstrData.nonce,
post_id: postId
}, function(response) {
if (status) status.innerText = response.success ? aimstrData.textDone : "Error: " + response.data;
});
}
');
}
/**
* Get all published post IDs from a site, sorted by dependency order.
*/
public function ajax_get_site_posts() {
check_ajax_referer( 'aimstr_generate', 'nonce' );
if ( ! current_user_can( 'manage_network' ) ) {
wp_send_json_error( 'Insufficient permissions.' );
}
$site_id = isset( $_POST['site_id'] ) ? (int) $_POST['site_id'] : 0;
if ( ! $site_id ) {
wp_send_json_error( 'Invalid site ID.' );
}
switch_to_blog( $site_id );
$posts = get_posts([
'post_type' => [ 'post', 'page' ],
'post_status' => 'any',
'posts_per_page' => -1,
'fields' => 'ids',
]);
$dependencies = [];
foreach ( $posts as $post_id ) {
$dependencies[ $post_id ] = [];
}
$site_url = get_site_url();
foreach ( $posts as $post_id ) {
$post = get_post( $post_id );
preg_match_all(
'/]*href=["\'](' . preg_quote( $site_url, '/' ) . '[^"\']*)["\'][^>]*>/i',
$post->post_content,
$matches
);
if ( empty( $matches[1] ) ) {
continue;
}
foreach ( array_unique( $matches[1] ) as $link ) {
$linked_id = url_to_postid( $link );
if ( $linked_id && $linked_id !== $post_id && in_array( $linked_id, $posts, true ) ) {
$dependencies[ $post_id ][] = $linked_id;
}
}
}
restore_current_blog();
$sorted = [];
$visited = [];
$visit = function( int $post_id ) use ( &$visit, &$sorted, &$visited, $dependencies ) {
if ( isset( $visited[ $post_id ] ) ) {
return;
}
$visited[ $post_id ] = true;
foreach ( $dependencies[ $post_id ] as $dep_id ) {
$visit( $dep_id );
}
$sorted[] = $post_id;
};
foreach ( $posts as $post_id ) {
$visit( $post_id );
}
wp_send_json_success([
'post_ids' => $sorted,
'total' => count( $sorted ),
]);
}
/**
* Translate post data to a given language.
*/
private function translate_post_data( array $source_data, string $language ): ?array {
$payload = json_encode([
'title' => $source_data['title'],
'content' => $source_data['content'],
]);
$default_prompt = "Translate the following JSON object to {$language}. Preserve all HTML/Shortcodes/Gutenberg markup in the content field. Do not add spaces before punctuation marks unless required by the grammar of {$language}. Return only valid JSON with the same keys, no markdown, no code fences, nothing else.\n\n{$payload}";
/**
* Filter the AI translation prompt.
*
* @param string $default_prompt The default prompt.
* @param array $source_data The source data being translated.
* @param string $language The target language.
*/
$prompt = apply_filters( 'aimstr_translate_prompt', $default_prompt, $source_data, $language );
$builder = wp_ai_client_prompt( $prompt )
->using_abilities( [ 'text_generation' ] )
->as_json_response( [
'type' => 'object',
'properties' => [
'title' => [ 'type' => 'string' ],
'content' => [ 'type' => 'string' ],
],
'required' => [ 'title', 'content' ],
'additionalProperties' => false,
] );
$provider = get_site_option( 'aimstr_provider', '' );
$model = get_site_option( 'aimstr_model', '' );
if ( ! empty( $provider ) ) {
$builder = $builder->using_provider( $provider );
}
if ( ! empty( $model ) ) {
$builder = $builder->using_model_preference( $model );
}
$result = $builder->generate_text();
if ( is_wp_error( $result ) ) {
$this->log( 'WP_Error: ' . $result->get_error_message() );
return null;
}
$parsed = json_decode( $result, true );
if ( ! $parsed || empty( $parsed['title'] ) || empty( $parsed['content'] ) ) {
$this->log( 'JSON parse error: ' . json_last_error_msg() );
return null;
}
return [
'title' => $parsed['title'],
'content' => $parsed['content'],
];
}
/**
* Rewrite internal links in translated content to point to the target site.
*/
private function rewrite_internal_links( string $content, int $source_site_id, int $target_site_id ): string {
$source_url = get_site_url( $source_site_id );
$target_url = get_site_url( $target_site_id );
$source_admin = get_admin_url( $source_site_id );
$target_admin = get_admin_url( $target_site_id );
$content = str_replace( $source_admin, $target_admin, $content );
preg_match_all(
'/]*href=["\'](' . preg_quote( $source_url, '/' ) . '[^"\']*)["\'][^>]*>/i',
$content,
$matches
);
if ( empty( $matches[1] ) ) {
return $content;
}
foreach ( array_unique( $matches[1] ) as $source_link ) {
if ( str_starts_with( $source_link, $target_url ) ) {
continue;
}
switch_to_blog( $source_site_id );
$source_post_id = url_to_postid( $source_link );
restore_current_blog();
if ( ! $source_post_id ) {
$content = str_replace( $source_link, str_replace( $source_url, $target_url, $source_link ), $content );
continue;
}
$group_id = $this->get_or_create_group_id( $source_site_id, $source_post_id );
switch_to_blog( $target_site_id );
$translated = get_posts([
'post_type' => 'any',
'post_status' => 'any',
'meta_key' => '_aimstr_translation_group',
'meta_value' => $group_id,
'numberposts' => 1,
'fields' => 'ids',
]);
if ( $translated ) {
$content = str_replace( $source_link, get_permalink( $translated[0] ), $content );
} else {
$content = str_replace( $source_link, str_replace( $source_url, $target_url, $source_link ), $content );
}
restore_current_blog();
}
return $content;
}
/**
* Translate a single post to all other network sites.
*/
public function ajax_translate_post() {
check_ajax_referer( 'aimstr_generate', 'nonce' );
if ( ! current_user_can( 'manage_network' ) ) {
wp_send_json_error( 'Insufficient permissions.' );
}
$source_site_id = isset( $_POST['site_id'] ) ? (int) $_POST['site_id'] : 0;
$post_id = isset( $_POST['post_id'] ) ? (int) $_POST['post_id'] : 0;
if ( ! $source_site_id || ! $post_id ) {
wp_send_json_error( 'Invalid parameters.' );
}
switch_to_blog( $source_site_id );
$source_data = $this->fetch_all_translatable_data( $post_id );
restore_current_blog();
if ( ! $source_data ) {
wp_send_json_error( "Post {$post_id} not found." );
}
$group_id = $this->get_or_create_group_id( $source_site_id, $post_id );
switch_to_blog( $source_site_id );
update_post_meta( $post_id, '_aimstr_translation_group', $group_id );
update_post_meta( $post_id, '_aimstr_is_source', true );
update_post_meta( $post_id, '_aimstr_source_site', $source_site_id );
update_post_meta( $post_id, '_aimstr_source_post', $post_id );
restore_current_blog();
$target_sites = get_sites( [ 'number' => 100 ] );
$results = [];
foreach ( $target_sites as $site ) {
if ( (int) $site->blog_id === $source_site_id ) {
continue;
}
$language = get_blog_option( $site->blog_id, 'WPLANG', '' ) ?: 'en_US';
$translated = $this->translate_post_data( $source_data, $language );
if ( ! $translated ) {
$results[] = [
'site_id' => $site->blog_id,
'status' => 'error',
'message' => "Site {$site->blog_id}: translation failed — check AI credits.",
];
continue;
}
$translated['content'] = $this->rewrite_internal_links(
$translated['content'],
$source_site_id,
(int) $site->blog_id
);
switch_to_blog( $site->blog_id );
$existing = get_posts([
'post_type' => $source_data['post_type'],
'post_status' => 'any',
'meta_key' => '_aimstr_translation_group',
'meta_value' => $group_id,
'numberposts' => 1,
'fields' => 'ids',
]);
if ( $existing ) {
$target_post_id = $existing[0];
wp_update_post([
'ID' => $target_post_id,
'post_title' => $translated['title'],
'post_content' => $translated['content'],
'post_status' => $source_data['post_status'],
]);
$action = 'updated';
} else {
$target_post_id = wp_insert_post([
'post_title' => $translated['title'],
'post_content' => $translated['content'],
'post_status' => $source_data['post_status'],
'post_type' => $source_data['post_type'],
]);
$action = 'created';
}
update_post_meta( $target_post_id, '_aimstr_translation_group', $group_id );
update_post_meta( $target_post_id, '_aimstr_source_site', $source_site_id );
update_post_meta( $target_post_id, '_aimstr_source_post', $post_id );
do_action( 'aimstr_after_post_inserted', $target_post_id, $translated, $site );
restore_current_blog();
$results[] = [
'site_id' => $site->blog_id,
'status' => 'success',
'message' => "Site {$site->blog_id}: {$action} successfully.",
];
}
wp_send_json_success([
'post_id' => $post_id,
'title' => $source_data['title'],
'results' => $results,
]);
}
}
require_once plugin_dir_path( __FILE__ ) . 'ai-multisite-translate-admin.php';
new AIMSTR();