dpps0715 2016-02-09 14:06
浏览 28
已采纳

需要了解查询帖子的复杂性

There's something I try to understand about the process of querying posts in wordpress:

Lets say I have this code:

$args = array{
    'cat' => 'animals',
    'posts_per_page' => 3
}

$the_query = new WP_Query($args);

So theoretically wordpress go to the database, going through all posts, and for each post, from the first to the last, it "asks" the post for it's category, if the answer is "animals" it grabs that post and move to the one after, if the category is something else, it skip that post and move to the one after. And repeat that process n times? Or, since I set posts_per_page to 3, after the third post that matchs "animals", the process it stops?

If the answer is the first, How can I optimize the code if, let's say I have 300 posts under "animals", but I need only the latest 3. How can I tell wordpress to stop checking after the third one that match "animals"?

I'm asking this since I'm working on a custom theme for site with more then 40000 posts, the homepage need to have at least 5 different queries like the one above, and I want to make it as efficient as possible.

I hope that's make sense.

Thanks in advance!

  • 写回答

1条回答 默认 最新

  • dongqiang1894 2016-02-09 14:20
    关注

    If you look into the WP core, you will see this piece of code in wp-includes/query.php, in the get_posts function:

    if ( empty($q['offset']) ) {
        $pgstrt = absint( ( $page - 1 ) * $q['posts_per_page'] ) . ', ';
    } else { // we're ignoring $page and using 'offset'
        $q['offset'] = absint($q['offset']);
        $pgstrt = $q['offset'] . ', ';
    }
    $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
    

    This mean that the posts_per_page parameter is translated to a basic sql LIMIT. So you don't have to worry for performance on this side.

    How does 'LIMIT' parameter work in sql?

    Considering the wp_terms_taxonomy.term_taxonomy_id, wp_terms_taxonomy.term_id_taxonomy, wp_term_relationships.term_taxonomy_id are all indexes the LIMIT should not select all rows, as far as I know.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据