Created
August 4, 2025 20:39
-
-
Save ideadude/cf73b49d80cca318a4dd7b417515d649 to your computer and use it in GitHub Desktop.
Encrypt/decrypt some options stored in the wp_options table.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Encrypt/decrypt some options stored in the wp_options table. | |
| * Note this will only work for options that are stored as strings. | |
| * | |
| * title: Encrypt/Decrypt Some Options | |
| * layout: snippet | |
| * collection: | |
| * category: | |
| * link: | |
| * | |
| * You can add this recipe to your site by creating a custom plugin | |
| * or using the Code Snippets plugin available for free in the WordPress repository. | |
| * Read this companion article for step-by-step directions on either method. | |
| * https://www.paidmembershipspro.com/create-a-plugin-for-pmpro-customizations/ | |
| */ | |
| // Array of options to encrypt. | |
| global $my_options_to_encrypt; | |
| $my_options_to_encrypt = array( | |
| 'pmpro_stripe_secretkey', | |
| 'stripe_publishablekey', | |
| ); | |
| // Set up filters to encrypt/decrypt options. | |
| foreach( $my_options_to_encrypt as $option ) { | |
| add_filter( "pre_update_option_{$option}", 'my_maybe_encrypt', 10, 3 ); | |
| add_filter( "option_{$option}", 'my_maybe_decrypt', 10 ); | |
| } | |
| /** | |
| * Decrypt options before they are returned. | |
| */ | |
| function my_maybe_decrypt( $value ) { | |
| // Bail if already decrypted. | |
| if ( substr( $value, 0, 5 ) !== '$HASH' ) { | |
| return $value; | |
| } | |
| // Remove the prefix and decrypt. | |
| return my_decrypt( substr( $value, 5 ) ); | |
| } | |
| /** | |
| * Encrypt options before they are saved. | |
| */ | |
| function my_maybe_encrypt( $new_value, $old_value, $option ) { | |
| // Bail if already encrypted. | |
| if ( substr( $new_value, 0, 5 ) === '$HASH' ) | |
| return $new_value; | |
| return '$HASH' . my_encrypt( $new_value ); | |
| } | |
| /** | |
| * A simple encryption function using OpenSSL. | |
| */ | |
| function my_encrypt($data, $key = null) { | |
| $key = $key ?: wp_salt(); | |
| $iv = openssl_random_pseudo_bytes(16); | |
| $encrypted = openssl_encrypt($data, 'aes-256-cbc', $key, 0, $iv); | |
| return base64_encode($iv . $encrypted); | |
| } | |
| /** | |
| * A simple decryption function using OpenSSL. | |
| */ | |
| function my_decrypt($data, $key = null) { | |
| $key = $key ?: wp_salt(); | |
| $data = base64_decode($data); | |
| $iv = substr($data, 0, 16); | |
| $encrypted = substr($data, 16); | |
| return openssl_decrypt($encrypted, 'aes-256-cbc', $key, 0, $iv); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment