DEV Community

Adil El Hallaoui
Adil El Hallaoui

Posted on

Auto-Translate WordPress Posts with GPT + WPML (Build Your Own Plugin)

Managing multilingual sites is hard. Writing the same post three times? Even harder. What if WordPress could auto-translate your posts into multiple languages the moment you hit “Publish”?
In this tutorial, we’ll build a WordPress plugin that connects WPML with GPT, automatically generating translated versions of your content.

✨ What You’ll Learn

  1. How to create a custom WordPress plugin
  2. How to hook into the save_post action
  3. How to use WPML APIs to manage translations
  4. How to integrate GPT for real-time translation

🔧 Step 1: Set Up the Plugin Skeleton
Inside wp-content/plugins/, create a folder:

auto-gpt-translator/
Enter fullscreen mode Exit fullscreen mode

Inside it, add a file: auto-gpt-translator.php

<?php
/**
 * Plugin Name: Auto GPT Translator for WPML
 * Description: Automatically translates WordPress posts into multiple languages using GPT and WPML.
 * Version: 1.0
 * Author: Your Name
 */

if ( ! defined( 'ABSPATH' ) ) exit;

class AutoGPTTranslator {

    public function __construct() {
        add_action('save_post', [$this, 'auto_translate_post'], 20, 2);
    }

    public function auto_translate_post($post_id, $post) {
        if ( wp_is_post_revision($post_id) ) return;

        $languages = apply_filters('wpml_active_languages', NULL, ['skip_missing' => 0]);

        if (!$languages) return;

        foreach ($languages as $lang => $details) {
            if ($lang === apply_filters('wpml_default_language', NULL)) continue;

            $this->translate_and_save($post_id, $post, $lang);
        }
    }

    private function translate_and_save($post_id, $post, $lang) {
        $translated_content = $this->call_gpt_translation($post->post_content, $lang);
        $translated_title   = $this->call_gpt_translation($post->post_title, $lang);

        do_action('wpml_update_translated_post', [
            'element_id'    => $post_id,
            'trid'          => apply_filters('wpml_element_trid', NULL, $post_id, 'post_post'),
            'language_code' => $lang,
            'source_language_code' => apply_filters('wpml_default_language', NULL),
            'post_content'  => $translated_content,
            'post_title'    => $translated_title,
        ]);
    }

    private function call_gpt_translation($text, $target_lang) {
        $api_key = get_option('auto_gpt_api_key');
        if (!$api_key) return $text;

        $response = wp_remote_post("https://api.openai.com/v1/chat/completions", [
            'headers' => [
                'Content-Type' => 'application/json',
                'Authorization' => "Bearer $api_key",
            ],
            'body' => json_encode([
                'model' => 'gpt-4o-mini',
                'messages' => [
                    ['role' => 'system', 'content' => "Translate the following text into $target_lang."],
                    ['role' => 'user', 'content' => $text]
                ],
            ]),
        ]);

        if ( is_wp_error($response) ) return $text;

        $body = json_decode(wp_remote_retrieve_body($response), true);

        return $body['choices'][0]['message']['content'] ?? $text;
    }
}

new AutoGPTTranslator();

Enter fullscreen mode Exit fullscreen mode

🔧 Step 2: Add a Settings Page
We need a simple admin page where you can paste your OpenAI API key.
Create settings.php inside the plugin folder:

<?php
add_action('admin_menu', function() {
    add_options_page(
        'Auto GPT Translator',
        'Auto GPT Translator',
        'manage_options',
        'auto-gpt-translator',
        'auto_gpt_translator_settings_page'
    );
});

add_action('admin_init', function() {
    register_setting('auto_gpt_translator_settings', 'auto_gpt_api_key');
});

function auto_gpt_translator_settings_page() {
?>
<div class="wrap">
    <h1>Auto GPT Translator Settings</h1>
    <form method="post" action="options.php">
        <?php settings_fields('auto_gpt_translator_settings'); ?>
        <?php do_settings_sections('auto_gpt_translator_settings'); ?>
        <table class="form-table">
            <tr valign="top">
                <th scope="row">OpenAI API Key</th>
                <td><input type="text" name="auto_gpt_api_key" value="<?php echo esc_attr(get_option('auto_gpt_api_key')); ?>" style="width: 400px;"/></td>
            </tr>
        </table>
        <?php submit_button(); ?>
    </form>
</div>
<?php
}

Enter fullscreen mode Exit fullscreen mode

⚙️ Step 3: How It Works

  1. You publish a post in your default WPML language.
  2. The plugin detects all other active languages.
  3. For each language, it sends the post title and content to GPT.
  4. WPML stores the new translated versions automatically.

🔒 Security Best Practices

  • Always use esc_attr() and sanitize_text_field() when saving settings.
  • Validate API responses with is_wp_error().
  • Consider adding rate limiting to avoid API overuse.
  • Never hardcode your API key in the plugin.

🚀 What You Just Built

You now have a production-ready WordPress plugin that:

  • Auto-translates posts with GPT
  • Integrates seamlessly with WPML
  • Lets you manage translations without manual copy-paste

Top comments (0)