How to Securely Store and Manage Plugin API Keys Using the WordPress 7.2 Secrets API

How to Securely Store and Manage Plugin API Keys Using the WordPress 7.2 Secrets API is one of the most important skills any WordPress developer or site administrator can have. Storing API keys directly in your plugin files or the database is a serious security risk. A single exposed key can compromise your entire application. WordPress 7.2 introduces a native Secrets API that gives you a dedicated, encrypted layer for storing sensitive credentials. In this tutorial, you’ll learn exactly how to register, retrieve, and rotate API keys using this new system. You’ll also learn how to avoid the common mistakes that leave keys vulnerable. By the end, your plugin credentials will be stored safely and managed cleanly.

Prerequisites and Requirements for Managing API Keys Securely

Before you start, make sure your environment meets the following requirements.

Software and access you’ll need:

  • WordPress 7.2 or higher installed and running
  • SSH access to your server (Linux recommended)
  • A code editor such as VS Code or Nano
  • WP-CLI installed on your server (optional but helpful)
  • Admin access to your WordPress dashboard

Assumed knowledge level:

You should be comfortable editing PHP files and working in a Linux terminal. Basic familiarity with WordPress plugin development helps. You don’t need to be an expert, but you should know what a hook and a function are.

Estimated time to complete: 30–45 minutes.

The WordPress 7.2 Secrets API stores credentials outside the standard wp_options table. It uses server-side encryption tied to your AUTH_KEY and SECURE_AUTH_KEY constants. This means even if your database is exposed, raw API keys won’t be readable. You can read more about WordPress security best practices in the official WordPress Security API documentation.

How to Securely Store and Manage Plugin API Keys Step by Step

Related tutorial: How to Harden Linux Server Security by Securing Filesystem Mount Options for /tmp, /dev/shm, and /proc on Ubuntu Server

Follow these steps carefully. Each one builds on the last.

Step 1: Verify your WordPress version

Log into your server via SSH and run this command to confirm you’re on 7.2 or higher.

wp core version --allow-root

If you’re below 7.2, run wp core update --allow-root before continuing. The Secrets API won’t exist on older versions.

Step 2: Confirm your security keys are set

Open your wp-config.php file and check that AUTH_KEY and SECURE_AUTH_KEY are defined with strong, unique values. These constants are what the Secrets API uses to encrypt stored credentials.

grep -E "AUTH_KEY|SECURE_AUTH_KEY" /var/www/html/wp-config.php

If these are missing or set to placeholder text, generate new ones from the WordPress secret key generator and paste them into your wp-config.php.

Step 3: Register a secret in your plugin

Open your plugin’s main PHP file. Add a registration call inside your plugin’s initialization hook. This tells WordPress what secrets your plugin needs.

add_action( 'init', function() {
    if ( function_exists( 'wp_register_secret' ) ) {
        wp_register_secret( 'my_plugin_api_key', array(
            'label'       => __( 'My Plugin API Key', 'my-plugin' ),
            'description' => __( 'API key for connecting to the My Plugin service.', 'my-plugin' ),
            'autoload'    => false,
        ) );
    }
} );

The autoload flag is set to false here. This means the secret won’t load on every page request. Only retrieve it when your plugin actually needs it.

Step 4: Store the API key value

Once the secret is registered, you can store the actual key value. Do this from your plugin’s settings save handler, not on every load.

if ( function_exists( 'wp_set_secret' ) ) {
    wp_set_secret( 'my_plugin_api_key', sanitize_text_field( $api_key_from_form ) );
}

Always sanitize the input before storing it. Never trust data coming from a form field directly.

Step 5: Retrieve the API key in your plugin logic

When your plugin needs to make an authenticated API call, retrieve the key like this.

$api_key = '';
if ( function_exists( 'wp_get_secret' ) ) {
    $api_key = wp_get_secret( 'my_plugin_api_key' );
}

if ( empty( $api_key ) ) {
    // Handle missing key gracefully
    return new WP_Error( 'missing_api_key', 'API key is not configured.' );
}

Never log or echo the value of $api_key. Treat it as sensitive at every point in your code.

Step 6: Delete a secret when it’s no longer needed

If a user disconnects your plugin or revokes their API key, remove it from storage immediately.

if ( function_exists( 'wp_delete_secret' ) ) {
    wp_delete_secret( 'my_plugin_api_key' );
}

This prevents stale credentials from sitting in your system indefinitely.

Step 7: Rotate the API key on a schedule

Key rotation is a critical security practice. Add a scheduled task to prompt users to rotate their key every 90 days.

if ( ! wp_next_scheduled( 'my_plugin_key_rotation_check' ) ) {
    wp_schedule_event( time(), 'daily', 'my_plugin_key_rotation_check' );
}

add_action( 'my_plugin_key_rotation_check', function() {
    $stored_date = get_option( 'my_plugin_key_stored_date' );
    if ( $stored_date && ( time() - $stored_date ) > ( 90  DAY_IN_SECONDS ) ) {
        // Trigger admin notice to rotate key
        update_option( 'my_plugin_key_rotation_needed', true );
    }
} );

Store the date when the key was first set using update_option( 'my_plugin_key_stored_date', time() ) inside your wp_set_secret() call handler.

Troubleshooting Common Issues with the WordPress Secrets API

Problem: wp_register_secret is undefined

This means you’re running a WordPress version below 7.2. Confirm your version with wp core version and update if needed.

Problem: Stored secret returns an empty string

Check that your AUTH_KEY and SECURE_AUTH_KEY haven’t changed since you stored the secret. If you regenerate these keys, all previously encrypted secrets become unreadable. Always back up your wp-config.php before changing security keys.

Problem: API calls fail after storing the key

Add temporary debug logging (never in production) to confirm the key is being retrieved correctly.

error_log( 'API key length: ' . strlen( $api_key ) );

This confirms the key exists without exposing its value in your logs.

Problem: Settings form isn’t saving the key

Make sure your form submission handler runs on a proper admin action hook with a nonce check. Without a valid nonce, WordPress will silently discard the submission.

check_admin_referer( 'my_plugin_save_settings' );

Warning: Don’t store API keys in wp_options as a fallback. It defeats the entire purpose of using the Secrets API.

Conclusion

You now know how to securely store and manage plugin API keys using the WordPress 7.2 Secrets API from start to finish. You’ve registered a secret, stored an API key, retrieved it safely, and set up key rotation. These steps protect your credentials from database exposure and reduce the blast radius of any potential breach. The Secrets API is a major step forward for WordPress plugin security. Your next steps could include building a full settings UI around this flow or extending it to manage multiple keys per plugin. Applying what you’ve learned here will make every plugin you build significantly more secure.

Similar Posts