admin管理员组文章数量:1122846
I am using WP_Object_Cache
to store entries under a group. This is done during an api request and I would like to return the total number of cached entries to the user in the response. After looking on the documentation there seems to be no way to get a list of all entries stored under a specific group without knowing the actual key for each entry.
public function handleRequest(\WP_REST_Request $request): ?\WP_REST_Response
{
global $wp_object_cache;
$content = $request->get_body();
if ($content) {
$group = 'sample';
$key = hash('sha256', $content);
$entry = $wp_object_cache->get($key, $group);
if (!$entry) {
// Process request.
$wp_object_cache->set($key, $content, $group);
}
return new \WP_REST_Response([
'status' => 200,
'response' => [
'entry' => $content,
// Here I would like to return the number of cached entries.
'numberOfEntries' => 1,
],
]);
}
}
I would like to do something like 'numberOfEntries' => array_keys($wp_object_cache->get_multiple('*', $group))
, but this only works if I actually already know all the keys for the stored entries?
I am using WP_Object_Cache
to store entries under a group. This is done during an api request and I would like to return the total number of cached entries to the user in the response. After looking on the documentation there seems to be no way to get a list of all entries stored under a specific group without knowing the actual key for each entry.
public function handleRequest(\WP_REST_Request $request): ?\WP_REST_Response
{
global $wp_object_cache;
$content = $request->get_body();
if ($content) {
$group = 'sample';
$key = hash('sha256', $content);
$entry = $wp_object_cache->get($key, $group);
if (!$entry) {
// Process request.
$wp_object_cache->set($key, $content, $group);
}
return new \WP_REST_Response([
'status' => 200,
'response' => [
'entry' => $content,
// Here I would like to return the number of cached entries.
'numberOfEntries' => 1,
],
]);
}
}
I would like to do something like 'numberOfEntries' => array_keys($wp_object_cache->get_multiple('*', $group))
, but this only works if I actually already know all the keys for the stored entries?
1 Answer
Reset to default 1Here is an untested one-liner, counting the cache data array returned from the magic __get
method, with a fallback to an empty array if the group key is not set:
'numberOfEntries' => count( $wp_object_cache->cache[$group] ?? [] );
Another approach is to consider bindTo to access the private cache array of the $wp_object_cache
instance via closure.
本文标签: rest apiHow can I get the number of items stored under a cache group
版权声明:本文标题:rest api - How can I get the number of items stored under a cache group 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736307504a1933331.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论