Open for Freelance & Projects
f in yt wp

WordPress Secrets API Tutorial: How to Encrypt & Secure AI API Keys (Stop Using wp_options)

Abdullah Nahian Updated: November 29, 2026 Reading Time: 6 mins

For over a decade, WordPress plugin developers have had no standardized, encrypted way to store sensitive API keys, OAuth client secrets, or webhook tokens. When site administrators paste an OpenAI, Gemini, or Stripe secret key into a plugin settings screen, almost every plugin calls update_option()—saving that credential in plain text inside the wp_options table. That means every SQL backup, staging clone, support export, or shared database query exposes live API keys.

The WordPress Secrets API (developed under Trac #66187 for the WordPress 7.2/7.3 cycle) solves this problem with core-native libsodium (XChaCha20-Poly1305) encryption, automatic key rotation slots, and safe object masking. In this developer guide, you will learn how to configure WP_SECRETS_KEY, store and retrieve AI API keys with wp_set_secret() and wp_get_secret(), migrate legacy plain-text options safely, and write backward-compatible fallback code.

How the WordPress Secrets API Works Under the Hood

Instead of forcing every plugin developer to roll custom OpenSSL or sodium wrappers, the Secrets API establishes a strict cryptographic separation between the database and the server filesystem:

  • Envelope Encryption with Libsodium: Secrets are encrypted using XChaCha20-Poly1305 via PHP’s bundled libsodium extension (with core’s sodium_compat fallback). Each secret key is derived from a random root key, which itself is encrypted using the WP_SECRETS_KEY constant in wp-config.php.
  • Safe WP_Secret Value Object: Calling wp_get_secret() never returns a raw string directly. It returns a WP_Secret instance that masks itself as [secret:my-plugin/api-key] if accidentally passed to echo, error_log(), json_encode(), or var_dump()—requiring an explicit $secret->reveal() call at the exact moment of use.
  • Built-In Two-Slot Key Rotation: Every secret maintains WP_Secret_Version::CURRENT and WP_Secret_Version::PREVIOUS slots, preventing mid-request failures during key rotation and letting you recover an overwritten key immediately.
  • Excluded from Public Endpoints: Ciphertext blobs are stored with autoload=no and are stripped from options.php and the REST API settings endpoint.

Step 1: Generate and Define WP_SECRETS_KEY in wp-config.php

The Secrets API requires a dedicated 32-byte base64-encoded master key in wp-config.php. Without a valid WP_SECRETS_KEY (reusing AUTH_KEY or leaving the sample placeholder will be rejected), wp_is_secrets_api_available() returns false and every read or write returns a secret_key_unavailable WP_Error.

Generate a cryptographically random key via your server terminal:

php -r 'echo base64_encode( random_bytes( 32 ) ), "\n";'

Paste the generated string into your wp-config.php file above the /* That's all, stop editing! */ line:

define( 'WP_SECRETS_KEY', 'paste-your-44-character-base64-key-here=' );

Step 2: Store, Reveal, and Rotate AI API Keys in Pure PHP

Always namespace your secret keys using your plugin slug (plugin-slug/secret-name). Note that core Secrets API functions do not perform capability checks internally—because they must remain callable inside WP-Cron jobs and background queues—so you must verify current_user_can( 'manage_options' ) in your form handler before calling wp_set_secret().

<?php
/**
 * Save an AI API key securely using the WordPress Secrets API.
 *
 * @param string $raw_api_key Plain-text API key submitted by an administrator.
 * @return bool|WP_Error
 */
function devnahian_save_openai_secret( #[\SensitiveParameter] $raw_api_key ) {
    if ( ! current_user_can( 'manage_options' ) ) {
        return new WP_Error( 'forbidden', __( 'Insufficient permissions.', 'devnahian' ) );
    }

    $clean_key = sanitize_text_field( wp_unslash( $raw_api_key ) );
    if ( empty( $clean_key ) ) {
        return new WP_Error( 'empty_key', __( 'API key cannot be empty.', 'devnahian' ) );
    }

    // Use Secrets API when available and host provider is writable
    if ( function_exists( 'wp_is_secrets_api_available' ) && wp_is_secrets_api_available() ) {
        if ( function_exists( 'wp_secrets_provider_is_writable' ) && ! wp_secrets_provider_is_writable() ) {
            return new WP_Error( 'readonly_provider', __( 'Secrets are managed at the host level.', 'devnahian' ) );
        }

        return wp_set_secret( 'devnahian-ai/openai-api-key', $clean_key );
    }

    // Backward-compatible fallback for older WordPress versions without Secrets API
    return update_option( 'devnahian_openai_api_key_fallback', $clean_key, false );
}

/**
 * Retrieve and reveal the API key only when making an outbound HTTP request.
 *
 * @return string|WP_Error
 */
function devnahian_get_openai_api_key() {
    if ( function_exists( 'wp_is_secrets_api_available' ) && wp_is_secrets_api_available() ) {
        $secret = wp_get_secret( 'devnahian-ai/openai-api-key' );

        if ( $secret instanceof WP_Secret ) {
            // Reveal at the last possible moment; never cache the revealed string
            return $secret->reveal();
        }

        if ( null === $secret ) {
            return new WP_Error( 'missing_secret', __( 'OpenAI API key has not been configured yet.', 'devnahian' ) );
        }

        // WP_Error: Secret exists in DB, but WP_SECRETS_KEY changed or cannot decrypt it
        return $secret;
    }

    $fallback = get_option( 'devnahian_openai_api_key_fallback', '' );
    return ! empty( $fallback )
        ? $fallback
        : new WP_Error( 'missing_secret', __( 'OpenAI API key is missing.', 'devnahian' ) );
}

Step 3: Migrate Existing Plain-Text Options Safely

If an existing plugin already stores an API key in wp_options, do not leave the plain-text row sitting in the database after upgrading. WordPress provides wp_import_option_as_secret() to copy an existing option into encrypted secret storage—automatically flagging it for rotation since the old value already lived in unencrypted backups—so you can delete the legacy option right afterward:

add_action( 'admin_init', 'devnahian_migrate_legacy_api_key_option' );

function devnahian_migrate_legacy_api_key_option() {
    if ( ! function_exists( 'wp_is_secrets_api_available' ) || ! wp_is_secrets_api_available() ) {
        return;
    }

    $legacy_option = 'devnahian_openai_api_key_fallback';
    $legacy_value  = get_option( $legacy_option, '' );

    if ( empty( $legacy_value ) ) {
        return;
    }

    $imported = wp_import_option_as_secret( $legacy_option, 'devnahian-ai/openai-api-key' );

    if ( true === $imported ) {
        delete_option( $legacy_option );
    }
}

4 Critical Rules for Working with WP_Secret Objects

  1. Never Treat WP_Error the Same as null: wp_get_secret() returns null only when a secret was never saved. If it returns a WP_Error, the encrypted record exists in the database but cannot be decrypted (for example, after cloning a site to staging without copying WP_SECRETS_KEY). Show a decryption warning instead of silently wiping out the stored credential.
  2. Check wp_secrets_provider_is_writable() Before Rendering Inputs: Managed WordPress hosts can wire external vaults (AWS Secrets Manager, HashiCorp Vault) via a secrets.php drop-in. On read-only host providers, wp_secrets_provider_is_writable() returns false, so your settings UI should display a notice rather than an editable password input.
  3. Never Serialize or Cache WP_Secret: Attempting to serialize() or clone a WP_Secret instance throws an exception by design. Fetch the secret and call ->reveal() immediately inside your API client wrapper.
  4. Add #[\SensitiveParameter] to Wrapper Functions: PHP 8.2+ redacts sensitive arguments from stack traces when marked with #[\SensitiveParameter], ensuring an uncaught exception never leaks a revealed API key into debug logs.

Final Thoughts

Plain-text API keys in wp_options have long been one of the weakest links in WordPress plugin security. By defining WP_SECRETS_KEY in wp-config.php, wrapping writes with wp_is_secrets_api_available(), and calling $secret->reveal() only at execution time, you protect your clients’ AI credentials from database leaks while keeping your plugins cleanly backward-compatible.