SO网友:O. Jones
我终于用这个函数解决了我的问题。它以竞争条件安全的方式附加到MySQL数据库中的瞬态。
/** Upsert and append data to a WordPress transient.
* This function deletes the transient from the WordPress options cache to avoid stale data.
* @param string $transient Transient name.
* @param string $value Data to append.
* @param int $expiration Transient expiration (default 120 sec). 0 means the transient does not expire.
* @param string $separator Separator between appended values (default \'|||\').
* @param int $maxlength Stop appending when value reaches this length to avoid bloat (default 512 KiB).
*/
function append_to_transient( $transient, $value, $expiration = 120, $separator = \'|||\', $maxlength = 524288 ) {
if ( ! $transient || strlen( $transient ) === 0 ) return;
if ( ! $value ) return;
try {
global $wpdb;
if ( $expiration ) {
$name = \'_transient_timeout_\' . $transient;
wp_cache_delete( $name, \'options\' );
$query = "INSERT IGNORE INTO $wpdb->options (option_name, option_value, autoload) VALUES (%s, %d, \'no\')";
$query = $wpdb->prepare( $query, $name, $expiration + time() );
$wpdb->get_results( $query );
}
$name = \'_transient_\' . $transient;
wp_cache_delete( $name, \'options\' );
$wpdb->get_results( $wpdb->prepare( "SET @upload = %s", $value ) );
$query = "INSERT INTO $wpdb->options (option_name, option_value, autoload) VALUES (%s, @upload, \'no\')"
. "ON DUPLICATE KEY UPDATE option_value ="
. "IF(%d > 0 AND LENGTH(option_value) <= %d - LENGTH(@upload),"
. "CONCAT(option_value, %s, @upload), option_value)";
$query = $wpdb->prepare( $query, $name, $maxlength, $maxlength, $separator );
$wpdb->get_results( $query );
} catch ( Exception $e ) {
/* empty, intentionally, don\'t crash when logging fails */
}
}