LoginSignup
7

More than 5 years have passed since last update.

WordPress Transients API を使うときの覚書

Last updated at Posted at 2017-01-13

Transients API とは

この API はキャッシュされるデータを一時的にデータベースへ保存するためのシンプルで標準化された方法を提供します。この方法ではデータに名前と有効期限を設定し、期限が来るとデータが削除されます。

利用例として

  • 各種SNSの数字(いいね数)などを自前で取得して表示
  • @horike37 の Simple GA ランキングプラグイン

基本コード

transient_sample.php
<?php
// Transient データを取得する
if ( WP_DEBUG or false === ( $value = get_transient( 'sample_key' ) ) ) {
    // Transient が存在しない場合 or デバッグモードのときにこの部分のコードが実行
    $value = ... // ここで $value の値を設定し直す
    // $value を Transient へ保存。12時間後に無効にする。
    set_transient( 'sample_key', $value, 12 * HOUR_IN_SECONDS );
}
echo $value;

Transients を削除したい/中身みたい

WP-CLIでサクッと


# Set transient.
$ wp transient set sample_key "test data" 3600
Success: Transient added.

# Get transient.
$ wp transient get sample_key
test data

# Delete transient.
$ wp transient delete sample_key
Success: Transient deleted.

# Delete expired transients.
$ wp transient delete --expired
Success: 12 expired transients deleted from the database.

# Delete all transients.
$ wp transient delete --all
Success: 14 transients deleted from the database.

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7