Sabuj Kundu 16th Nov 2026


WordPress 7.2 introduces a significant security improvement for plugin developers: the Secrets API. For years, WordPress plugins have relied on the Options API to store API keys, OAuth tokens, SMTP passwords, and other sensitive credentials. The problem? These values were commonly stored in the database as plain text.

The new Secrets API provides a standardized way to store encrypted credentials, retrieve them when needed, and manage credential rotation. It also introduces an extensible architecture that allows hosting providers to integrate external secret management systems.

In this guide, we will explore the WordPress 7.2 Secrets API, understand its architecture, and walk through practical PHP examples that plugin developers can use in real-world projects.

1. What Is the WordPress Secrets API?

The WordPress Secrets API is a new core API introduced in WordPress 7.2 for securely managing sensitive information such as API keys, authentication tokens, OAuth client secrets, and external service credentials.

Previously, developers typically used get_option() and update_option() to manage credentials. Although these functions are convenient, sensitive values stored through the Options API are generally available as readable database values.

The Secrets API introduces encrypted storage, a standardized retrieval mechanism, version management, and support for alternative storage providers.

Why does WordPress need a Secrets API?

Consider a typical WordPress plugin that connects to an external service such as an email marketing platform, payment gateway, cloud storage provider, or AI API.

The plugin might save credentials like this:

$api_key = 'sk-example-secret-key';

update_option( 'my_plugin_api_key', $api_key );

// Retrieve the API key.
$api_key = get_option( 'my_plugin_api_key' );

This works, but the API key is stored in the WordPress database as plain text. Anyone who obtains a database dump or accesses the relevant database records may be able to read the credential.

Some common exposure scenarios include:

  • Database backups shared with developers or contractors.
  • Staging environments created from production database copies.
  • Database exports stored in cloud storage.
  • SQL injection vulnerabilities that expose database records.
  • Debugging and support workflows that accidentally expose configuration data.
  • Credentials appearing in database inspection tools or exports.

WordPress 7.2 addresses this problem by providing a dedicated API for encrypted credential storage.

2. What’s New in WordPress 7.2 Secrets API?

The Secrets API introduces several important capabilities for developers and hosting providers.

Feature Description
Encrypted storage Credentials are encrypted before being stored in the database.
Standardized API Plugins can use WordPress core functions instead of implementing their own encryption systems.
Secret versioning The previous credential version is retained when a new value is saved.
Secret retirement Developers can explicitly retire an old credential version after rotation.
Masked values Secret objects hide their actual values when printed, logged, or inspected.
Custom providers Hosting providers can integrate external secret management systems.
Multisite support Separate site-level and network-level secret storage is supported.
Site Health integration WordPress can report encryption, configuration, and credential rotation issues.

One important distinction: WordPress 7.2 provides the underlying API, not a complete graphical credential management interface. A dedicated administration interface is planned for a future release.

3. Important Functions in the WordPress Secrets API

WordPress 7.2 introduces a collection of functions for managing secrets. These functions provide a consistent interface for plugin developers.

3.1. wp_set_secret()

Use wp_set_secret() to create a new secret or update an existing one.

wp_set_secret( 'my-plugin/api-key', $api_key );

The first parameter is the secret name, and the second parameter is the sensitive string you want to store.

Secret names should follow the convention plugin-slug/secret-name. For example:

wp_set_secret( 'my-plugin/api-key', $api_key );

wp_set_secret( 'my-plugin/client-secret', $client_secret );

wp_set_secret( 'my-plugin/smtp-password', $smtp_password );

wp_set_secret( 'my-plugin/openai-api-key', $openai_api_key );

The function returns true on success or a WP_Error if the operation fails.

3.2. wp_get_secret()

Use wp_get_secret() to retrieve a previously stored credential.

$secret = wp_get_secret( 'my-plugin/api-key' );

if ( $secret instanceof WP_Secret ) {
    $api_key = $secret->reveal();
}

The function can return three different results:

  • WP_Secret: The secret exists and can be retrieved.
  • null: The secret has never been stored.
  • WP_Error: The secret exists but cannot currently be retrieved.

This distinction is important. Do not treat an encryption or storage error as an absent credential. Doing so could cause your plugin to unnecessarily request a new API key and overwrite an existing credential.

3.3. WP_Secret::reveal()

The WP_Secret object deliberately masks its value when printed or inspected. To obtain the actual credential, developers must explicitly call reveal().

$secret = wp_get_secret( 'my-plugin/api-key' );

if ( $secret instanceof WP_Secret ) {
    $api_key = $secret->reveal();

    // Use the credential immediately.
    $client = new My_API_Client( $api_key );
}

This explicit operation makes it easier to identify where sensitive values are accessed in a codebase.

Avoid logging the revealed value, storing it in unnecessary variables, or retaining the secret object in a cache.

3.4. wp_delete_secret()

Use wp_delete_secret() to permanently remove a secret and its stored versions.

$result = wp_delete_secret( 'my-plugin/api-key' );

if ( is_wp_error( $result ) ) {
    error_log( 'Unable to delete the API credential.' );
}

This is useful when an administrator disconnects an integration, removes an API configuration, or uninstalls a plugin.

3.5. wp_retire_secret_version()

When a credential is updated, WordPress retains the previous version. This is useful during API key rotation because an integration may need time to transition from the old credential to the new one.

After confirming that the old credential is no longer required, use wp_retire_secret_version() to remove the previous version.

wp_retire_secret_version(
    'my-plugin/api-key',
    WP_Secret_Version::PREVIOUS
);

The API supports the current and previous version slots through the WP_Secret_Version class.

3.6. wp_list_secrets()

The Secrets API also provides wp_list_secrets(), which returns secret names and metadata rather than exposing the actual credential values.

This can be useful when building a plugin settings screen that needs to display which credentials have been configured.

For example, a plugin could use this functionality to show administrators that an API credential exists without displaying the actual API key.

3.7. wp_import_option_as_secret()

This function is particularly useful for existing plugins that already store credentials through the Options API.

It copies an existing option value into encrypted secret storage and flags the imported credential for rotation. It does not automatically delete the original option.

$result = wp_import_option_as_secret(
    'my_plugin_api_key',
    'my-plugin/api-key'
);

if ( is_wp_error( $result ) ) {
    // Handle the import failure.
}

Developers should remove the original option only after confirming that the import succeeded and the new credential can be retrieved.

4. Practical Example: Building a Secrets API Integration

Let’s build a simple example for a WordPress plugin that connects to an external service using an API key.

Step 1: Save an API key

Imagine an administrator submits an API key through your plugin settings page. After validating the request, save the key using the Secrets API.

function my_plugin_save_api_key( $api_key ) {

    if ( ! wp_is_secrets_api_available() ) {
        return new WP_Error(
            'secrets_api_unavailable',
            'The WordPress Secrets API is not available.'
        );
    }

    if ( ! wp_secrets_provider_is_writable() ) {
        return new WP_Error(
            'secrets_provider_read_only',
            'This hosting environment manages credentials externally.'
        );
    }

    $api_key = sanitize_text_field( $api_key );

    if ( empty( $api_key ) ) {
        return new WP_Error(
            'empty_api_key',
            'Please provide a valid API key.'
        );
    }

    return wp_set_secret(
        'my-plugin/api-key',
        $api_key
    );
}

In a real settings handler, also verify the administrator’s capability and the WordPress nonce before accepting the submitted value.

Step 2: Retrieve the API key

Create a reusable function that retrieves the credential whenever your plugin needs to communicate with the external service.

function my_plugin_get_api_key() {

    if ( ! wp_is_secrets_api_available() ) {
        return new WP_Error(
            'secrets_api_unavailable',
            'The Secrets API is unavailable.'
        );
    }

    $secret = wp_get_secret( 'my-plugin/api-key' );

    if ( is_wp_error( $secret ) ) {
        return $secret;
    }

    if ( null === $secret ) {
        return new WP_Error(
            'api_key_missing',
            'The API key has not been configured.'
        );
    }

    return $secret->reveal();
}

Step 3: Use the API key in an external API request

You can now retrieve the credential and use it in an HTTP request.

function my_plugin_send_api_request( $endpoint ) {

    $api_key = my_plugin_get_api_key();

    if ( is_wp_error( $api_key ) ) {
        return $api_key;
    }

    $response = wp_remote_get(
        esc_url_raw( $endpoint ),
        array(
            'timeout' => 20,
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
                'Accept'        => 'application/json',
            ),
        )
    );

    if ( is_wp_error( $response ) ) {
        return $response;
    }

    return $response;
}

The important point is that your plugin does not need to implement its own encryption and decryption logic. WordPress handles the underlying secret storage mechanism.

5. Integrating the Secrets API Into a Plugin Settings Page

Most commercial and free WordPress plugins have a settings page where administrators configure API keys and third-party integrations.

The Secrets API can be integrated into these existing settings pages without changing the user experience significantly.

For example, your settings page might contain an API key field:

<?php
$secret = wp_get_secret( 'my-plugin/api-key' );

$has_api_key = $secret instanceof WP_Secret;
?>

<form method="post" action="">

    <?php wp_nonce_field(
        'my_plugin_save_settings',
        'my_plugin_nonce'
    ); ?>

    <label for="my_plugin_api_key">
        API Key
    </label>

    <input
        type="password"
        id="my_plugin_api_key"
        name="my_plugin_api_key"
        value=""
        autocomplete="new-password"
        placeholder="Enter a new API key"
    >

    <p class="description">
        <?php
        echo $has_api_key
            ? esc_html__( 'An API key is already configured. Enter a new value to replace it.', 'my-plugin' )
            : esc_html__( 'No API key has been configured.', 'my-plugin' );
        ?>
    </p>

    <button type="submit" name="save_api_key">
        Save API Key
    </button>

</form>

Notice that the existing API key is never populated into the input field. This avoids exposing the actual credential in the HTML source.

The form handler should check the nonce, user permissions, and provider write capability before saving the submitted credential.

Also remember that wp_get_secret() can return a WP_Error. A settings screen should distinguish a configured credential from a temporarily unreadable credential instead of treating every error as an empty value.

6. Credential Rotation With the Secrets API

Credential rotation is an important security practice. API keys should be replaced periodically and immediately when a potential exposure is discovered.

Before WordPress 7.2, developers generally needed to implement their own credential replacement and backup mechanisms.

The Secrets API makes this process more consistent by retaining a previous version when a new value is written.

Example: Updating an API key

$new_api_key = 'new-example-api-key';

$result = wp_set_secret(
    'my-plugin/api-key',
    $new_api_key
);

if ( is_wp_error( $result ) ) {
    // The new credential was not stored.
    return $result;
}

// The previous credential is retained.
return true;

When the new key is saved, the existing current version moves to the previous version slot.

Example: Reading the previous API key

$previous_secret = wp_get_secret(
    'my-plugin/api-key',
    WP_Secret_Version::PREVIOUS
);

if ( $previous_secret instanceof WP_Secret ) {

    $previous_api_key = $previous_secret->reveal();

    // Use only when a controlled fallback is required.
}

A developer may temporarily use the previous credential while an external integration is being migrated. This fallback should be deliberate and limited to the relevant integration workflow.

Example: Retiring the previous version

$result = wp_retire_secret_version(
    'my-plugin/api-key',
    WP_Secret_Version::PREVIOUS
);

if ( is_wp_error( $result ) ) {
    // Handle retirement failure.
}

Do not retire the previous credential immediately after saving a new one if external systems or running requests still depend on it. The API does not automatically determine when an integration has finished transitioning.

7. Migrating Existing API Keys From the Options API

This is one of the most important use cases for existing WordPress plugins.

If your plugin already stores API keys using update_option(), you can gradually migrate existing installations to the new Secrets API.

WordPress provides wp_import_option_as_secret() specifically for this purpose.

Example: Import an existing API key

function my_plugin_migrate_api_key() {

    if ( ! wp_is_secrets_api_available() ) {
        return false;
    }

    if ( ! wp_secrets_provider_is_writable() ) {
        return new WP_Error(
            'secrets_provider_read_only',
            'The configured secret provider is read-only.'
        );
    }

    $old_api_key = get_option( 'my_plugin_api_key', '' );

    if ( empty( $old_api_key ) ) {
        return false;
    }

    $result = wp_import_option_as_secret(
        'my_plugin_api_key',
        'my-plugin/api-key'
    );

    if ( is_wp_error( $result ) ) {
        return $result;
    }

    // Verify that the imported secret can be retrieved.
    $secret = wp_get_secret( 'my-plugin/api-key' );

    if ( ! $secret instanceof WP_Secret ) {
        return new WP_Error(
            'secret_import_verification_failed',
            'Unable to verify the imported API key.'
        );
    }

    // Remove the old plaintext option after successful verification.
    delete_option( 'my_plugin_api_key' );

    return true;
}

The import function does not automatically remove the original option. This is intentional because developers need to control the migration process.

Important security consideration:
Importing a credential does not remove copies of that credential from existing database backups, staging databases, replicas, or previously exported files. The imported secret is flagged for rotation. Replace the original external API key and update the stored credential to complete the security migration.

Supporting older WordPress versions

If your plugin supports WordPress versions older than 7.2, you should maintain backward compatibility.

A possible implementation is to use the Secrets API when available and retain the legacy Options API for older WordPress versions.

function my_plugin_store_api_key( $api_key ) {

    if (
        function_exists( 'wp_is_secrets_api_available' ) &&
        wp_is_secrets_api_available()
    ) {

        if ( ! wp_secrets_provider_is_writable() ) {
            return new WP_Error(
                'secret_provider_read_only',
                'The secret is managed by the hosting provider.'
            );
        }

        return wp_set_secret(
            'my-plugin/api-key',
            $api_key
        );
    }

    // Legacy compatibility for older WordPress versions.
    return update_option(
        'my_plugin_api_key',
        $api_key,
        false
    );
}

For production plugins, keep the storage and retrieval paths consistent. Do not silently fall back to plaintext Options API storage when the Secrets API exists but its provider is unavailable or read-only. An actual storage error should be reported rather than weakening the security model.

8. Secrets API and WordPress Multisite

WordPress 7.2 also supports network-level secret management for Multisite installations.

This is particularly useful for plugins that provide network-wide services, shared integrations, or centralized API connections.

The API provides separate network-level functions, including:

  • wp_set_network_secret()
  • wp_get_network_secret()
  • wp_delete_network_secret()
  • wp_retire_network_secret_version()

For example, a network administrator could save a shared API credential:

$result = wp_set_network_secret(
    'my-plugin/api-key',
    $api_key
);

To retrieve the network-level credential:

$secret = wp_get_network_secret(
    'my-plugin/api-key'
);

if ( $secret instanceof WP_Secret ) {
    $api_key = $secret->reveal();
}

Site-level and network-level secrets are separate. The API does not automatically fall back from one storage scope to the other.

9. How Does the WordPress Secrets API Encrypt Credentials?

Understanding the encryption architecture helps developers make better decisions when implementing the API.

WordPress 7.2 uses libsodium encryption with the XChaCha20-Poly1305 construction to protect stored credentials.

The architecture uses a random root key and derived encryption keys. The root key is itself encrypted using a dedicated key configured in wp-config.php.

The WP_SECRETS_KEY constant

The Secrets API requires the WP_SECRETS_KEY constant.

Add the following configuration to your wp-config.php file:

define(
    'WP_SECRETS_KEY',
    'YOUR_BASE64_ENCODED_RANDOM_32_BYTE_KEY'
);

Generate a suitable random key using PHP:

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

New WordPress installations automatically receive this configuration. Existing installations should check the Site Health recommendations and add the generated key to wp-config.php.

Important: Do not casually change WP_SECRETS_KEY

Once secrets have been stored, changing or removing WP_SECRETS_KEY can make existing credentials unreadable.

It is not interchangeable with the normal WordPress authentication salts. It must be preserved securely and included in your deployment and disaster recovery procedures.

If you need to replace the key, follow the official WordPress key rotation procedure, including temporarily configuring the previous key through WP_SECRETS_KEY_PREVIOUS.

10. Custom Secret Storage Providers

One of the most interesting aspects of the Secrets API is that WordPress does not force every installation to use the default database-backed storage.

Hosting companies and advanced deployments can integrate external secret management platforms.

WordPress 7.2 provides three important extension points through a wp-content/secrets.php drop-in:

Extension point Purpose
WP_Secrets_Keyring Controls how the root key is protected and retrieved.
WP_Secrets_Store Controls where encrypted secret records are stored.
WP_Secrets_Provider Allows an external provider to manage the complete Secrets API.

For example, a hosting provider might integrate AWS Key Management Service, AWS Secrets Manager, HashiCorp Vault, or another external credential management platform.

Example: Custom keyring drop-in

The following illustrates the structure of a custom keyring implementation. The actual encryption and key management operations must be implemented according to the external provider’s API.

<?php
// wp-content/secrets.php

class My_Host_Keyring extends WP_Secrets_Keyring {

    public function wrap(
        #[\SensitiveParameter] string $key_material
    ) {
        // Integrate with your external KMS.
    }

    public function unwrap( string $wrapped ) {
        // Retrieve and decrypt key material.
    }

    public function get_key_source(): string {
        return 'My Hosting Provider KMS';
    }
}

$wp_secrets_keyring = new My_Host_Keyring();

This is an architectural example, not a complete production KMS adapter. A real implementation must follow the required method contracts, handle provider failures, and pass the WordPress Secrets API conformance tests.

The drop-in can also provide a custom store or a complete provider. When an external backend fails, the API returns an error instead of silently falling back to local storage.

11. Working With Read-Only Secret Providers

Some hosting providers manage credentials outside WordPress. For example, administrators may configure secrets through a hosting dashboard, deployment pipeline, or command-line tool.

In this situation, the WordPress application may be allowed to retrieve credentials but not create or update them.

Use wp_secrets_provider_is_writable() to determine whether the current provider supports writing.

if ( ! wp_secrets_provider_is_writable() ) {

    // Display an informational message.
    echo esc_html__(
        'API credentials are managed by your hosting provider.',
        'my-plugin'
    );

    return;
}

$result = wp_set_secret(
    'my-plugin/api-key',
    $api_key
);

if ( is_wp_error( $result ) ) {
    // Display or log an appropriate error.
}

Never silently fall back to storing credentials in the Options API when a provider is read-only. That would defeat the purpose of the external security configuration.

12. Important Security Considerations and Limitations

The Secrets API significantly improves credential storage, but developers should understand what it does and does not protect against.

12.1. It does not isolate credentials between plugins

The namespace convention, such as my-plugin/api-key, prevents accidental naming collisions. It does not create plugin-specific access permissions.

Any code executing within the WordPress application can potentially call wp_get_secret() and retrieve a known secret name.

Therefore, the Secrets API should not be treated as a complete isolation mechanism between plugins.

12.2. It does not protect against arbitrary code execution

If an attacker can execute arbitrary PHP code inside your WordPress installation, that attacker may be able to retrieve secrets through the same API used by legitimate plugins.

12.3. Always verify user permissions

The Secrets API functions do not automatically enforce the capabilities of the user submitting or managing credentials.

Your plugin must implement appropriate permission checks.

if ( ! current_user_can( 'manage_options' ) ) {
    wp_die(
        esc_html__(
            'You are not allowed to manage API credentials.',
            'my-plugin'
        )
    );
}

12.4. Never expose revealed values unnecessarily

  • Do not print API keys in HTML responses.
  • Do not include secrets in error messages.
  • Do not write credentials to debug logs.
  • Do not expose credentials through REST API responses.
  • Do not place secrets in JavaScript variables unless absolutely necessary.
  • Do not cache revealed credential values without a clear security requirement.

12.5. Use the correct API availability checks

Before using the API for migration or credential storage, check wp_is_secrets_api_available().

A missing key, an unavailable drop-in, or an unreadable root key can make the API unavailable. A backend failure during an individual operation can also return a WP_Error.

13. Secrets API and WordPress Site Health

WordPress 7.2 also integrates Secrets API diagnostics into the Site Health interface.

Administrators can inspect the configuration through:

WordPress Dashboard → Tools → Site Health

The Security section includes checks related to:

  • Whether the Secrets API encryption key is properly configured.
  • Whether stored secrets can be decrypted.
  • Whether imported credentials are still pending rotation.

The Site Health Info tab also provides information about the active provider, keyring, key source, and number of stored secrets.

This is particularly useful for plugin support teams because they can identify configuration problems without asking administrators to disclose their actual API credentials.

14. WordPress Plugin Developer Checklist

If you maintain a WordPress plugin that connects to external services, consider the following implementation checklist when adopting the Secrets API.

  • Identify every API key, password, token, and sensitive credential currently stored in plugin options.
  • Introduce a dedicated secret name using your plugin slug as the namespace.
  • Use wp_set_secret() to store new credentials.
  • Use wp_get_secret() and reveal() to retrieve credentials.
  • Handle null and WP_Error separately.
  • Check whether the Secrets API is available before using it.
  • Check provider write capability before presenting credential input fields.
  • Implement an upgrade routine using wp_import_option_as_secret().
  • Verify successful imports before deleting legacy options.
  • Encourage credential rotation after importing existing plaintext values.
  • Implement proper capability and nonce verification.
  • Maintain compatibility with older supported WordPress versions.
  • Test credential rotation, provider failures, and database migration scenarios.
  • Ensure that no sensitive values are exposed through logs, REST responses, or HTML output.

15. Conclusion: A Better Security Foundation for WordPress Plugins

The WordPress 7.2 Secrets API is an important step toward standardizing how WordPress plugins manage sensitive credentials.

Instead of every plugin developer implementing a separate encryption mechanism, WordPress now provides a common foundation for encrypted storage, retrieval, version management, and external secret providers.

For developers building payment integrations, email delivery systems, AI-powered plugins, CRM connections, analytics tools, or other third-party integrations, this API provides a more consistent way to handle sensitive credentials.

Existing plugin developers should start reviewing their credential storage implementations, planning migration paths, and testing against the WordPress 7.2 beta releases.

The bigger opportunity is not simply replacing update_option() with wp_set_secret(). It is building a more secure and maintainable credential management architecture across the WordPress ecosystem.

As WordPress continues to evolve, adopting standardized security APIs will become increasingly important for building reliable, scalable, and production-ready plugins.

Further Reading and References

Explore these resources to learn more about WordPress plugin development, security, and integrations:

Need a Custom WordPress Plugin or Integration?

Building a WordPress plugin that connects with external APIs, payment gateways, email platforms, or AI services? Security, scalability, and maintainability should be part of the architecture from day one.

At Codeboxr, we have been building WordPress plugins, custom integrations, and web applications since 2011. Our developers focus on clean, secure, and production-ready solutions.

Let’s Discuss Your Project