← Tous les articles

Adding an AI feature to WordPress without exposing your API key

A "summarise" or "rewrite" button in WordPress takes an afternoon. Shipping your AI provider's key inside the JavaScript takes one visitor to regret it. Here is how to route the call through a protected REST endpoint, with quotas and proper error handling.

Adding an AI feature to WordPress without exposing your API key

Key points

  • Your AI provider’s key must never reach the browser, minified bundle or not.
  • A WordPress REST route acts as the middleman: it checks the user, validates the input and calls the API.
  • A per-user quota and an explicit timeout protect both your bill and your server.

Requests to add AI to WordPress sites keep coming: summarise a long post into an excerpt, suggest alt text, rewrite a product description. The API call itself is a handful of lines. The real question is where those lines live. On several sites we have taken over, the provider key sat in the theme’s JavaScript, readable by anyone who opened the page source and free to use on the site owner’s account.

The rule: the browser only talks to WordPress

The browser sends its request to your site, your site checks who is asking and what for, and only then does the server call the AI provider with the key. The key lives in wp-config.php or an environment variable, never in the database and never in Git.

// wp-config.php: define( 'WTS_AI_API_KEY', '...' ); define( 'WTS_AI_ENDPOINT', 'https://...' );

add_action( 'rest_api_init', function () {
    register_rest_route( 'wts/v1', '/resume', array(
        'methods'             => 'POST',
        'permission_callback' => function () {
            return is_user_logged_in();
        },
        'args'                => array(
            'texte' => array(
                'type'              => 'string',
                'required'          => true,
                'sanitize_callback' => 'sanitize_textarea_field',
                'validate_callback' => function ( $value ) {
                    return is_string( $value ) && mb_strlen( $value ) <= 4000;
                },
            ),
        ),
        'callback'            => 'wts_ai_resume',
    ) );
} );

The permission_callback is what makes this safe. Without it the route is public, and so is your AI budget. Depending on the feature, swap is_user_logged_in() for a tighter check such as current_user_can( 'edit_posts' ) for an editor-only tool.

The server-side call and its guard rails

The callback caps requests per user, sets a timeout, and never forwards the provider’s raw error to the browser.

function wts_ai_resume( WP_REST_Request $request ) {
    $user_id = get_current_user_id();
    $quota   = 'wts_ai_quota_' . $user_id;
    $count   = (int) get_transient( $quota );

    if ( $count >= 20 ) {
        return new WP_Error( 'quota', 'Limite quotidienne atteinte.', array( 'status' => 429 ) );
    }

    $response = wp_remote_post( WTS_AI_ENDPOINT, array(
        'timeout' => 20,
        'headers' => array(
            'Authorization' => 'Bearer ' . WTS_AI_API_KEY,
            'Content-Type'  => 'application/json',
        ),
        'body'    => wp_json_encode( array(
            'instructions' => 'Résume le texte en trois phrases, en français.',
            'input'        => $request['texte'],
        ) ),
    ) );

    if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
        error_log( 'AI call failed: ' . print_r( $response, true ) );
        return new WP_Error( 'ai_error', 'Service indisponible.', array( 'status' => 502 ) );
    }

    set_transient( $quota, $count + 1, DAY_IN_SECONDS );

    $data = json_decode( wp_remote_retrieve_body( $response ), true );
    return array( 'resume' => wp_strip_all_tags( $data['output'] ?? '' ) );
}

The exact request and response shape depends on your provider, so map the fields to its documentation; the overall pattern stays the same. Note the wp_strip_all_tags() on the way out: treat model output like any other external input, which may contain markup you did not ask for.

In the browser: a plain fetch

The JavaScript only needs WordPress’s REST nonce, which proves the request comes from a logged-in session on your own site.

const res = await fetch('/wp-json/wts/v1/resume', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-WP-Nonce': wtsAi.nonce, // from wp_localize_script(): wp_create_nonce( 'wp_rest' )
  },
  body: JSON.stringify({ texte: textarea.value }),
});

Show a loading state and disable the button while the call runs. AI responses often take several seconds, and a user who clicks three times spends three requests.

Mistakes we have seen

  • Sending personal data to the provider without covering it in the privacy policy. Filter what leaves the site and tell users.
  • Keeping the default timeout, so a slow provider ties up a PHP worker. Set it explicitly.
  • Saving the AI output straight into the content. Suggest it, and let a human approve it.

FAQ

Can the key go in the plugin settings instead?

It can, if the client needs to change it themselves, but it then sits in the database and is visible to administrators. A constant in wp-config.php is the better default when possible.

Is a transient-based quota reliable?

For an internal tool, yes. For public-facing features or heavy traffic, move the counter to a dedicated table or to Redis.

Want to bring AI into your WordPress site or web app safely, with costs under control? We design and build these integrations end to end, from the interface to the server side.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →