WordPress.org

Ready to get started?Download WordPress

Forums

Counting posts? (3 posts)

  1. Workshopshed
    Member
    Posted 1 year ago #

    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 p.id = 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.

  2. bcworkz
    Member
    Posted 1 year ago #

    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.

  3. Workshopshed
    Member
    Posted 1 year ago #

    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.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.