Support » Plugins » Hacks » Counting posts?

  • I’ve been working on the blogger importer plugin and just watched Andrew Nacin’s video on writing better plugins.

    One of the things he mentioned is not to make direct queries on the DB because this will bypass the caching mechanisms and it ties the code to the DB tables hence making it more vulnerable to future changes.

    There are some examples in the importer where we get the count of all the records by looking at the meta data.

    function count_imported_posts($bloghost)
                global $wpdb;
                $sql = $wpdb->prepare("SELECT count(post_id) as cnt FROM $wpdb->postmeta  m
                                    inner join $wpdb->posts p on = m.post_id and post_type = 'post'
                                     where meta_key = '%s' and meta_value = '%s'",'blogger_blog', $bloghost);
                $result = $wpdb->get_results($sql);

    So my question is:

    Is it better to do this or to use get_posts or something else? My concern is that get_posts will have to get all of the records as objects which could use a lot of memory.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz


    I’d be foolish to second guess Nacin, but I do wonder if he was referring to direct DB queries using PHP mySQL functions rather than $wpdb methods. While I really should, I don’t have time right now to view the video to get better insight.

    The $wpdb object does have a rudimentary caching mechanism, and it does insert a layer between you and the actual table structure, making it adaptable to future DB changes. So I think you are fine doing what you are doing, your concern is legitimate, but just my opinion, no one else’s.

    Thanks BC, I think I’ll stick with getting the DB to count the records as it should be able to do that a lot more efficiently than the WordPress.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Counting posts?’ is closed to new replies.