WordPress 7.2 introduces the Secrets API, a native system for securely managing credentials and API keys directly within the platform. For publishers and developers integrating advanced language models (such as Gemini 3.7, Claude Opus 5, Llama 4) and third-party APIs, this represents a crucial step towards compliance with enterprise security standards and data protection regulations (GDPR, European AI Act).
The WordPress 7.2 Secrets API allows you to store, encrypt, and manage sensitive credentials without exposing keys in the source code, unprotected databases, or configuration files. This article analyzes the technical implementation, integration patterns with LLM services, end-to-end encryption mechanisms, and regulatory compliance strategies.
Architecture of the Secrets API WordPress 7.2
The Secrets API is based on four architectural pillars: centralized storage, Encryption at rest, Key lifecycle management e audit logging. Unlike previous solutions based on PHP constants defined in wp-config.php, this API offers a structured and auditable approach.
Storage and Encryption Model
The credentials are stored in the table wp_options with the prefix wp_secret_. Every secret is encrypted using AES-256-GCM (Advanced Encryption Standard at 256 bit with Galois/Counter Mode) to ensure both data confidentiality and authenticity. The main encryption key (KEK – Key Encryption Key) is derived from the combination of:
- Salt WORDPRESS_AUTH_KEY and WORDPRESS_SECURE_AUTH_KEY from wp-config.php
- Unique identifier of the site (site URL hash)
- Timestamp of creation of the key for planned rotation
This model ensures that the credentials remain unusable even in the event of exporting the database, since the encrypted value is cryptographically linked to the specific configuration of the WordPress instance.
Programming Interface
The Secrets API exposes three main functions:
wp_secret_set( $identifier, $secret, $group = '')– Stores an encrypted credentialwp_secret_get( $identifier, $group = '')– Retrieves the decrypted value in memorywp_secret_delete( $identifier, $group = '')– Delete a secret with secure overwrite
The parameter $group It allows you to organize the secrets by category (e.g., ‘gemini’, ‘claude’, ‘stripe’), making it easier to manage and audit the credentials associated with specific integrations.
Integration with LLM and Third-Party APIs
Managing API keys for LLM services represents a primary use case for the Secrets API. Each provider (Google Cloud, Anthropic, Meta) requires credentials with specific privileges; the Secrets API allows for isolating these access points and limiting exposure in the event of compromise.
Configuration for Gemini 3.7 and the Google Cloud API
To integrate Gemini 3.7, the Google Cloud API key must be stored using the Secrets API:
// API key storage
wp_secret_set(
'gemini_api_key',
'AIzaSy[...full username...]',
'google_ai'
);
// Recovery in a helper class
class Gemini_Client {
private $api_key;
public function __construct() {
$this->api_key = wp_secret_get( 'gemini_api_key', 'google_ai' );
if ( empty( $this->api_key ) ) {
throw new Exception( 'Gemini API key not configured' );
}
}
public function analyze_image( $image_url ) {
$response = wp_remote_post(
https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-vision:generateContent','
array(
'headers' => array(
'Content-Type' => 'application/json',
'x-goog-api-key' => $this->api_key,
( ),
'body' => wp_json_encode(array(
'contents' => array(
'parts' => array(
array( 'text' => 'Analyze this image',
array( 'inline_data' => array(
'mime_type' => 'image/jpeg',
'data' => base64_encode( file_get_contents( $image_url ) ),
) ),
( ),
( ),
) ),
)
);
return json_decode(wp_remote_retrieve_body( $response ), true);
}
}
This pattern ensures that the API key never appears in logs, caches, or stack traces. In the event of an error, WordPress only logs the ‘gemini_api_key’ identifier, not the actual value.
Multi-Provider Pattern for Llama 4 and Claude Opus 5
When implementing a multi-LLM architecture (e.g., Llama 4 self-hosted + Claude Opus 5 for fallback), the Secrets API simplifies managing multiple credentials:
// Configurazione centralizzata
wp_secret_set( 'claude_api_key', 'sk-ant-[...]', 'anthropic' );
wp_secret_set( 'claude_model', 'claude-opus-5', 'anthropic' );
wp_secret_set( 'llama_endpoint', 'https://llama.internal.local:8000', 'llama' );
wp_secret_set( 'llama_auth_token', 'Bearer [...]', 'llama' );
// Router intelligente basato su disponibilità
class LLM_Router {
public function route_request( $prompt, $modality = 'text' ) {
// Prova Llama 4 self-hosted per ridurre latenza
try {
$llama_client = new Llama_Client(
wp_secret_get( 'llama_endpoint', 'llama' ),
wp_secret_get( 'llama_auth_token', 'llama' )
);
return $llama_client->complete( $prompt );
} catch ( Exception $e ) {
// Fallback a Claude Opus 5
error_log( 'Llama unavailable, switching to Claude: ' . $e->getMessage() );
$claude_client = new Claude_Client(
wp_secret_get( 'claude_api_key', 'anthropic' )
);
return $claude_client->complete( $prompt );
}
}
}
This approach centralizes the management of credentials, facilitates the rotation of keys, and allows for auditing all sensitive operations from a single point.
End-to-end encryption mechanisms
The Secrets API implements idle encryption, but for high-security scenarios (fintech, healthcare, sensitive newsrooms) it is advisable to add an additional level of end-to-end application encryption.
Additional Symmetric Encryption with libsodium
WordPress 7.2 supports natively sodium_crypto_secretbox() for additional symmetric encryption. This is useful for credentials intended for specific critical operations:
// Classe helper per crittografia aggiuntiva
class Secret_Vault {
private $master_key;
public function __construct() {
// La chiave master viene archiviata in wp_secret con protezione nativa
$this->master_key = wp_secret_get( 'vault_master_key', 'security' );
}
public function encrypt_sensitive( $plaintext ) {
$nonce = random_bytes( SODIUM_CRYPTO_SECRETBOX_NONCEBYTES );
$ciphertext = sodium_crypto_secretbox(
$plaintext,
$nonce,
$this->master_key
);
// Restituisci nonce + ciphertext concatenati
return base64_encode( $nonce . $ciphertext );
}
public function decrypt_sensitive( $encrypted ) {
$data = base64_decode( $encrypted );
$nonce = substr( $data, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES );
$ciphertext = substr( $data, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES );
$plaintext = sodium_crypto_secretbox_open(
$ciphertext,
$nonce,
$this->master_key
);
if ( false === $plaintext ) {
throw new Exception( 'Decryption failed: corrupted data' );
}
return $plaintext;
}
}
This approach implements a deep defense model: the master key is protected by the native Secrets API, while sensitive data receives an additional layer of application encryption.
Key derivation for specific integrations
To extend security, unique keys can be derived for each integration using HKDF (HMAC-based Key Derivation Function):
// Generation of unique keys for specific providers
function derive_provider_key( $provider_name, $master_secret ) {
$info = 'wp-secrets-v1|' . $provider_name . '|' . ABSPATH;
$derived = hash_hkdf(
'sha256',
$master_secret,
length: 32, // 256 bit
info: $info
);
return $derived;
}
// Use
$gemini_key = wp_secret_get( 'gemini_api_key', 'google_ai' );
$derived_key = derive_provider_key('gemini', $gemini_key);
// Now $derived_key is unique to Gemini on this site
This model allows for the logical separation of credentials per provider, facilitating granular revocation and audit trail.
Audit Logging and GDPR/AI Act Compliance
The WordPress 7.2 Secrets API integrates an automatic logging audit system. However, for full compliance (GDPR Art. 32, AI Act Annex I), it is necessary to extend the recording with contextual metadata.
Implementation of Structured Audit Trail
Create a dedicated table for the audit of sensitive operations:
// Hook per registrare accessi a segreti
add_action( 'wp_secret_accessed', function( $identifier, $group ) {
global $wpdb;
$wpdb->insert(
$wpdb->prefix . 'secret_audit_log',
array(
'timestamp' => current_time( 'mysql', true ),
'user_id' => get_current_user_id(),
'action' => 'secret_access',
'secret_identifier' => $identifier,
'secret_group' => $group,
'ip_address' => sanitize_text_field( $_SERVER['REMOTE_ADDR'] ?? '' ),
'user_agent' => sanitize_text_field( $_SERVER['HTTP_USER_AGENT'] ?? '' ),
'result' => 'success',
),
array( '%s', '%d', '%s', '%s', '%s', '%s', '%s', '%s' )
);
}, 10, 2 );
// Hook per errori di accesso
add_action( 'wp_secret_access_denied', function( $identifier, $group, $reason ) {
global $wpdb;
$wpdb->insert(
$wpdb->prefix . 'secret_audit_log',
array(
'timestamp' => current_time( 'mysql', true ),
'user_id' => get_current_user_id(),
'action' => 'secret_access_denied',
'secret_identifier' => $identifier,
'secret_group' => $group,
'ip_address' => sanitize_text_field( $_SERVER['REMOTE_ADDR'] ?? '' ),
'user_agent' => sanitize_text_field( $_SERVER['HTTP_USER_AGENT'] ?? '' ),
'result' => 'failure',
'error_reason' => $reason,
),
array( '%s', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )
);
}, 10, 3 );
This audit trail is essential to demonstrate compliance with Article 32 of the GDPR (technical and organizational measures) and with the AI Act for high-risk systems.
Compliance Documentation for Language Models
When using the Secrets API to manage LLM credentials, it is necessary to document:
- Data Processing Agreement (DPA) with the providers (Google, Anthropic, Meta)
- Retention Policy: how long the secrets remain archived
- Rotation Schedule: rotation speed of the keys (recommended: 90 days)
- Incident Response Plan: immediate revocation procedure in case of compromise
For European newsrooms and publishers, compliance with the’AI Act It requires tracking which LLM models process which categories of editorial data. The Secrets API facilitates this segregation:
// Metadata for AI Act compliance
$llm_config = array(
'model_identifier' => 'gemini-3.7-vision',
'risk_category' => 'high-risk', // according to the AI Act
'data_categories' => array( 'editorial_content', 'user_analytics' ),
'jurisdiction' => 'EU',
'gdpr_article' => '6(1)(f)', // legal basis
'processing_limitation' => array(
'max_requests_per_day' => 10000,
'retention_days' => 30,
( ),
);
wp_secret_set(
json_encode( $llm_config ),
'gemini_config_v1',
'llm_compliance'
);
This metadata facilitates the automatic generation of Data Provenance Records and Model Cards, which are essential for European compliance.
Advanced Strategies: Key Rotation and Zero-Trust Architecture
In enterprise environments, periodic key rotation is essential. WordPress 7.2 Secrets API supports non-disruptive rotation through versioning:
Implementation of Granular Key Rotation
// Class to manage rotation of keys
class Secret_Rotation_Manager {
private $rotation_interval = 7776000; // 90 days in seconds
The public function should_rotate( $secret_identifier, $group ) should be called only when the group is rotated.
$last_rotation = get_option(
"wp_secret_rotation_{$group}_{$secret_identifier}"
);
if ( ! $last_rotation ) {
return true;
}
return (current_time( 'timestamp') - $last_rotation) > $this->rotation_interval;
}
public function rotate_key( $secret_identifier, $group, $new_secret ) {
// Step 1: Archive the new version with a suffix
$version = wp_date('YmdHis');
wp_secret_set(
"{$secret_identifier}_v{$version}",
$new_secret,
$group
);
// Step 2: Update the pointer to the latest version
update_option(
"wp_secret_active_{$group}_{$secret_identifier}",
$version
);
// Step 3: Record the rotation timestamp
update_option(
"wp_secret_rotation_{$group}_{$secret_identifier}",
current_time( 'timestamp')
);
// Step 4: Log for audit
error_log(
sprintf(
'Secret rotated: %s/%s (version: %s)',
$group,
$secret_identifier,
$version
)
);
}
public function get_active_secret( $secret_identifier, $group ) {
$active_version = get_option(
"wp_secret_active_{$group}_{$secret_identifier}"
);
if ( $active_version ) {
return wp_secret_get(
"{$secret_identifier}_v{$active_version}",
$group
);
}
//Fallback to the version without versioning
return wp_secret_get( $secret_identifier, $group );
}
}
This pattern allows for zero-downtime credential rotation, crucial for production services.
Zero-Trust Access Control for Secrets
Implement capability-based access control to limit which roles and plugins can access specific secrets:
// Registration of secrets with access policies
function register_secret_with_policy( $identifier, $group, $secret, $access_policy ) {
wp_secret_set( $identifier, $secret, $group );
// Policy structure
$policy = array(
'allowed_roles' => array( 'administrator', 'editor' ),
'allowed_plugins' => array( 'gemini-integration', 'claude-assistant' ),
'allowed_files' => array( '/wp-content/plugins/gemini-integration/class-client.php' ),
'ip_whitelist' => array( '10.0.0.0/8' ), // internal
);
update_option(
"wp_secret_policy_{$group}_{$identifier}",
$policy
);
}
// Middleware for enforcing policy
function wp_secret_get_with_policy( $identifier, $group = '') {
$policy = get_option( "wp_secret_policy_{$group}_{$identifier}" );
if ( ! $policy ) {
return wp_secret_get( $identifier, $group );
}
// Check user role
$user = wp_get_current_user();
if ( ! array_intersect( $user->roles, $policy['allowed_roles'] ) ) {
do_action(
'wp_secret_access_denied',
$identifier,
$group,
'insufficient_role'
);
return null;
}
// Check IP origin (for zero-trust)
$client_ip = sanitize_text_field( $_SERVER['REMOTE_ADDR'] ?? '' );
if ( ! $this->ip_in_cidr( $client_ip, $policy['ip_whitelist']) ) {
do_action(
'wp_secret_access_denied',
$identifier,
$group,
'ip_not_whitelisted'
);
return null;
}
return wp_secret_get( $identifier, $group );
}
This implementation ensures that sensitive credentials are accessible only by authorized actors, aligning with the zero-trust principle of modern security.
Integration with Configuration Management Tools
For multi-site environments and automated deployments, it is advisable to integrate the Secrets API with Infrastructure-as-Code tools:
Synchronization with HashiCorp Vault
For enterprise architectures, WordPress can synchronize secrets with HashiCorp Vault:
// Plugin adapter for HashiCorp Vault
class Vault_Secret_Provider {
private $vault_addr;
private $vault_token;
public function __construct( $vault_addr, $vault_token ) {
$this->vault_addr = $vault_addr;
$this->vault_token = $vault_token;
}
public function sync_to_wordpress($vault_path, $identifier, $group) {
$response = wp_remote_get(
"{$this->vault_addr}/v1/{$vault_path}",
array(
'headers' => array(
'X-Vault-Token' => $this->vault_token,
( ),
)
);
if ( is_wp_error( $response ) ) {
error_log( 'Vault sync failed: ' . $response->get_error_message() );
return false;
}
$data = json_decode(
wp_remote_retrieve_body( $response ),
true
);
if ( isset( $data['data']['date']['value'] ) ) {
wp_secret_set(
$identifier,
$data['date']['date']['value'],
$group
);
return true;
}
return false;
}
public function monitor_expiration( $vault_path, $identifier, $group ) {
// Checks expiration metadata from Vault
// and perform automatic rotation if necessary
}
}
This pattern enables a single source of truth for credential management, with a centralized audit trail.
Common Best Practices and Anti-Patterns
✓ Best Practices:
- Always use wp_secret_set() for credentials, never explicit configuration variables
- Implement key rotation every 90 days as a baseline
- Record every access to secrets for a complete audit trail
- Separating credentials by provider/environment (production vs staging)
- Use least-privilege for access policies
- Monitor anomalies (massive visits, unusual hours)
✗ Anti-pattern to avoid:
- Do not store secrets in wp-config.php with the available Secrets API
- Do not log decrypted values in debug log
- Do not share the master key between multiple WordPress sites
- Do not implement overly permissive access policies (‘administrator’ at all)
- Do not overlook the compliance documentation for critical secrets
FAQ
Is the WordPress 7.2 Secrets API compatible with legacy plugins that use configuration constants?
Yes. WordPress 7.2 maintains backward compatibility with constants defined in wp-config.php. However, it is recommended to perform a progressive migration to the Secrets API to improve security posture. A helper wrapper can abstract the credential origin, allowing for ordered fallback to legacy constants if the secret is not stored via the Secrets API.
How to manage the automatic rotation of third-party API keys (e.g., Google Cloud, Anthropic) without downtime?
Implement a versioning pattern as described in the Key Rotation section: archive the new key with a version suffix, update the active pointer, and provide a grace period (24-48 hours) during which the client attempts the active version and fallback to the previous one in case of an 401/403 error. This allows the provider to rotate the key in the background without service interruption.
Does the WordPress 7.2 Secrets API meet the end-to-end encryption requirements of the European AI Act for high-risk systems?
The Secrets API provides dormant encryption (AES-256-GCM), which is robust. However, to fully comply with the AI Act (Annex I, Annex III), it is necessary to: (1) add additional application encryption with libsodium, (2) implement structured audit trails with compliance metadata, (3) document Data Processing Agreements with LLM providers, and (4) implement zero-trust access control as described. The Secrets API provides the basic infrastructure, but compliance is the responsibility of the implementer.
Can I use the Secrets API to store database and FTP credentials in addition to external API keys?
Technically yes, but it is not recommended. Secrets API is optimized for third-party credentials (API keys, tokens). For database and FTP credentials, which are critical for the site's availability, it is preferable to use wp-config.php with file-level permissions strict (600) and logical separation of environments. The Secrets API is complementary to, not a replacement for, traditional WordPress system configuration.
How do I integrate the Secrets API with automated CI/CD workflows and deployments?
Use post-deployment webhook to synchronize secrets from a centralized source (HashiCorp Vault, AWS Secrets Manager, Google Cloud Secret Manager) to the WordPress target. The deployment orchestrator (GitHub Actions, GitLab CI) should inject secrets via HTTP API (not via direct database). This allows immutable deployment code, with credentials managed separately from dedicated infrastructure.
Conclusion
La WordPress 7.2 Secrets API It represents a qualitative leap in credential management for platforms that integrate LLMs and third-party APIs. Through native encryption (AES-256-GCM), structured audit trail, and a clean programmatic interface, this API enables the implementation of security best practices without compromising usability.
For publishers and developers operating in European jurisdictions, the Secrets API facilitates regulatory compliance (GDPR Art. 32, AI Act Annex I). However, end-to-end security requires a layered approach: native encryption + additional application encryption (libsodium) + audit trail + zero-trust access control + automated key rotation.
The implementation should start with a auditing the current credentials, To identify which secrets are exposed in the code or configuration files. Subsequently, implement the progressive migration to the Secrets API, starting with the most critical credentials (LLM, payment processor), with rigorous testing in a staging environment before the rollout to production.
For highly complex scenarios (multi-site, enterprise environment, high compliance), integrating the Secrets API with centralized secret management systems (Vault, AWS Secrets Manager) ensures scalability and full auditability of the entire credential supply chain.



