Php 更有效的Wordpress查询解析?(获取帖子($query))
计算查询返回的帖子数量并分析返回的帖子的最有效方法(时间方面)是什么 第1部分: 我目前有以下代码:Php 更有效的Wordpress查询解析?(获取帖子($query)),php,wordpress,parsing,Php,Wordpress,Parsing,计算查询返回的帖子数量并分析返回的帖子的最有效方法(时间方面)是什么 第1部分: 我目前有以下代码: /* $query = { 'numberposts' = '15', 'queryvar1' = '…', 'queryvar2' = '…'; } */ $lastposts = get_posts($query); // This uses the original query, and will only return 15 results $print['returnedcount'
/* $query = {
'numberposts' = '15',
'queryvar1' = '…',
'queryvar2' = '…';
}
*/
$lastposts = get_posts($query); // This uses the original query, and will only return 15 results
$print['returnedcount'] = count($lastposts); // Uses some resources (+ acceptable time)
$query['numberposts'] = "-1"; // Get total results from query
$print['totalposts'] = count(get_posts($query)); // Uses lots of resources (+ lots of time)
我不需要第二个get_posts($query)
-提供给我的其他数据,我如何加快速度?我只需要计算查询返回的帖子总数(除了numberposts
-值)
第二部分:
$lastposts
-对象稍后将用于获取帖子数据(ID、日期、标题、评论计数、缩略图和作者ID)
这些数据输入到$print
-数组中,如下所示:
foreach ($lastposts as $post){
// ID
$print['id'][] = (string)$post->ID;
// Date
$print['date'][] = (string)$post->post_date;
// Title
$print['title'][] = (string)$post->post_title;
// Comment count
$print['comments'][] = (string)$post->comment_count;
// Images
$image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'medium');
$print['image'][] = (string)$image[0];
$imageRetina = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'large');
$print['imageretina'][] = (string)$imageRetina[0];
// Author
$print['author'][] = (string)$post->post_author;
}
有没有更省时的方法呢?我注意到图像操作确实需要相当长的时间
非常感谢!在第一部分中,您可以创建一个新对象,而不是使用
get\u posts
。这应该比您问题中的代码更有效,但差异可能可以忽略不计
$query = new WP_Query();
$query->query(array(
'posts_per_page' => 15
));
$print['returnedcount'] = $query->post_count;
$print['totalposts'] = $query->found_posts;
您是否可以在第一次运行查询时使用所需的内容填充数组?这将使运行
get\u posts()
变得不必要
因此,在模板文件中
while( have_posts() ): the_post();
// do your normal output here e.g. the_content(); etc.
$print['title'][] = get_the_title();
// any more data you want to collect.
endwhile;
您可以将整个数据收集位移动到functions.php。您是否也使用缓存?这可能会有所帮助。(例如,我正在开发一个插件,通过AJAX请求运行,因此使用循环不是一个选项,不幸的是:)您是否可以使用会话变量来存储在循环过程中获得的信息,然后在收到ajax请求时使用这些信息?这就是我最后要做的。非常感谢!:)