2

我正在使用 Wordpress 并为其开发了一些特定于站点的插件,另外我的主题是定制的,以适应后端插件的要求。

最后几天我在 Wordpress 中摆弄瞬态。在一些教程中,他们说“如果您正在使用自定义查询并且它们的结果是可缓存的:使用瞬态”。听起来不错,但我想知道何时使用瞬变来获得真正的优势。我的意思是,即使使用瞬态,也必须在后台至少有两个查询,不是吗?第一个用于检查有效性,第二个用于瞬态本身。

那么使用瞬态即自定义WP_Query真的有用吗?非常感谢您的帮助和想法。

4

1 回答 1

3

看起来相当简单。它是一个文字类助手,允许您以“memcache”类型的方式存储对象。您首先设置瞬态

function do_something_here($callback_param = 'value'){
  $key = 'do_something_' . $callback_param;//set the name of our transient equal to the value of the callback param being passed in the function.
  $my_query = get_transient($myKey);  //if we've stored this request before, then use it.
  if($my_query !=== false){
    //we found a previous existing version of this query. let's use it.
    return $my_query;
  }else{
    //it doesn't exist, we need to build the transient.
    //do our database querying here, global $wpdb; etc
    //We are going to pretend our returned variable is 'george'
    $value = george;
    $length = 60*60*24; //how long do we want the transient to exist? 1 day here.
    set_transient($key, $value, $length);
    return $value;
  }
}

现在我们已经创建了触发器并将其绑定到“$key”的名称,我们可以通过使用 key 所暗示的确切值(我们之前声明的)随时访问它。

echo 'I wanted to do something, so : ' . do_something('value') . ' is what i did! ';

通过使用这种格式,您可以将查询保存在类似“缓存”的世界中,并使用它们来生成您的响应。这在某种程度上类似于在 MySql 中使用“触发”事件。事实上,这是通常称为长轮询的技术的一部分。

于 2012-03-07T08:46:58.980 回答