Home > Back-end >  Wordpress plugin - where to store a custom API Key?
Wordpress plugin - where to store a custom API Key?

Time:02-28

I am making a wordpress plugin and need to store a custom API key. The user will copy an API key from my website and then paste it into an input in Wordpress. I need to store this API key in Wordpress to make future requests. The question is, where should this be stored?

I have tried posting to a custom handler using ajax and storing it using define:

function my_ajax_set_api_key_handler()
{
    // if post request contains api key, set it using define
    if (isset($_POST['apiKey'])) {
        define('MY_API_KEY', $_POST['apiKey']);
        // return success
        echo json_encode(array('success' => true));
    } else {
        // if post request doesn't contain api key, set it to empty string
        define('MY_API_KEY', '');
        // return error
        echo json_encode(array('success' => false));
    }

    wp_die();
}

but later, trying to retrieve this API key using:

constant('MY_API_KEY');

returns null when if I refesh the Wordpress page, so it does not persist. How do you store an API key persisently in Wordpress? I see most suggest to store it in wp-config.php, but I am not sure how to store it there programmatically, which I need to be able to do.

CodePudding user response:

You can save its in Database. The easy way is to use update_option:

update_option('your_prefix_api_key', 'MY_API_KEY');

and get its with get_option:

get_option('your_prefix_api_key');
  • Related