loops - 限制从 WP_Query 或 'get' 函数返回的 wordpress 字段

标签 loops slug wordpress

希望限制 WP 查询的返回字段,以帮助加快来自服务器的响应并减少检索的数据量。对于我使用的查询,它最多只需要 3 个数据字段,其余的通过循环中的 ACF get_field_object 引入。我正在使用的其他函数(例如 get_posts 或 get_terms)具有字段选项,但仅限于少数内容,例如仅“slug”或“id => slug”。

我习惯于在 CakePHP 中进行开发,它可以选择指定要返回的每个字段,但是该项目需要 wordpress 来实现其他功能,因此我非常有限。

TL;DR 需要加快从 Wordpress 获取帖子的速度

最佳答案

我在查询中使用了 fields 参数并在此查询上运行了 get posts。
例如:在我的例子中,我只需要获取多个类别的 Post id,所以我创建了一个这样的查询:

$the_query = new WP_Query( array( 
                        'ignore_sticky_posts' => 1,
                        'posts_per_page'      => -1,
                        'cat'                 => '2,6,7' ,
                        'fields'              => 'ids',
                        'post_type'           => 'post',
                        'post_status'         => 'publish', 
                                ) 
                        );

在此查询上运行 get_posts:
$posts = $the_query->get_posts();

$posts 将仅获取特定类别帖子的 ID。

或者也可以使用标准和流行的方式完成,即通过运行 have_posts 循环:
if ( $the_query->have_posts() ) {
        while ( $the_query->have_posts() ) {
            $the_query->the_post();
            $post_id_array[] = get_the_ID(); 
        }           
    }

这是帮助加快来自服务器的响应和减少检索的数据量的两种方法

关于loops - 限制从 WP_Query 或 'get' 函数返回的 wordpress 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26420726/

相关文章:

c - 将带有 float 的txt文件读入二维矩阵

c - 这不是逐字节比较 : WHY

JavaScript/jQuery - 拦截循环

javascript - PHP/JS : convert PHP array to JavaScript array

非英文字符的java slugify字符串

php - 根据星期几显示 PHP 对象

php - 使用 slug url 从 mysql 数据库获取文章

codeigniter - 如何从 url codeigniter 中删除参数

wordpress - Woocommerce,管理员通过 wp-admin 添加时更新价格

mysql - 组合多个 WordPress 数据库查询