I want to use Transient API as cookie, but I want to know if it is the best practice,and how to make transient be unique or per user. Thanks


In almost all circumstances, a cookie would be preferable to a transient. WP has a really bad habit of not cleaning up transients properly, so unless your code cleans up after itself (Kills useless transients) they will just sit forever in your DB. Even transients that are set to expire sometimes don't.

In terms of uniqueness, you'd generate a transient like so:

set_transient( $transient_name, $data_to_store, $expiration_time_in_seconds);

so to create a transient that would be user-specific would be something like:

$transient_name = 'name_this_whatever' . $user_id;
$expiration_time_in_seconds =  60*60*12;
set_transient( $transient_name, $data_to_store, $expiration_time_in_seconds);

Then later on, to retrieve the same field you'd just do:

$transient_name = 'name_this_whatever' . $user_id;
get_transient( $transient_name );

You might want to take a look at this SO discussion here for a discussion about when transients may be best utilized.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.