Using WordPress ‘pre_set_transient_{$transient}’ PHP filter

The pre_set_transient_{$transient} WordPress PHP filter allows you to modify a specific transient value before it’s set in the database.

Usage

add_filter('pre_set_transient_transient_name', 'your_custom_function', 10, 3);

function your_custom_function($value, $expiration, $transient) {
  // your custom code here
  return $value;
}

Parameters

  • $value (mixed): The new value of the transient.
  • $expiration (int): Time until expiration in seconds.
  • $transient (string): The transient name.

More information

See WordPress Developer Resources: pre_set_transient_{$transient}

Examples

Modify the value of a specific transient

In this example, we will modify the value of a transient named ‘sample_transient’ before it’s set:

add_filter('pre_set_transient_sample_transient', 'modify_sample_transient', 10, 3);

function modify_sample_transient($value, $expiration, $transient) {
  $value .= ' - Modified!';
  return $value;
}

Increase the expiration time of a transient

In this example, we will increase the expiration time of a transient named ‘sample_transient’ by 60 seconds:

add_filter('pre_set_transient_sample_transient', 'increase_expiration_time', 10, 3);

function increase_expiration_time($value, $expiration, $transient) {
  $expiration += 60;
  set_transient($transient, $value, $expiration);
  return false;
}

Add a prefix to the transient name

In this example, we will add a prefix to the transient name before it’s set:

add_filter('pre_set_transient_sample_transient', 'add_prefix_to_transient_name', 10, 3);

function add_prefix_to_transient_name($value, $expiration, $transient) {
  $transient = 'myprefix_' . $transient;
  set_transient($transient, $value, $expiration);
  return false;
}

Validate transient data

In this example, we will validate the transient data before it’s set. If the data is not valid, we will return an error message as the transient value:

add_filter('pre_set_transient_sample_transient', 'validate_transient_data', 10, 3);

function validate_transient_data($value, $expiration, $transient) {
  if (!is_array($value)) {
    return 'Error: Invalid data.';
  }
  return $value;
}

Log transient changes

In this example, we will log the changes made to a specific transient named ‘sample_transient’:

add_filter('pre_set_transient_sample_transient', 'log_transient_changes', 10, 3);

function log_transient_changes($value, $expiration, $transient) {
  error_log("Transient '{$transient}' has been updated. New value: " . print_r($value, true));
  return $value;
}