how does $wpdb differ to WP_Query?

I’m going to write a function to return the next/prev post in a specific category. can anyone tell me what the differences would be in using $wpdb as opposed to WP_Query(); eg new WP_Query(args)? what determines which of these should be used?

cheers,
Gregory

Related posts

Leave a Reply

3 comments

  1. The wpdb class is the interface with the database. WP_Query uses wpdb to query the database. You should use WP_Query when dealing with the native WordPress tables, to integrate your code properly with the WordPress environment. Use wpdb directly when you need to access data in your own tables.

  2. Pay attention that wp_query() doesn’t exist in WP core, so I think almost nobody of us can tell you what is it.

    $wpdb is object of the wpdb class, which provides ability to prepare and run database queries.

    I’m going to write a function to return the next/prev post in a specific category

    Use next_post_link/previous_post_link functions to do it.

    Updated: To better understand when you have to use WP_Query read this thread When to use WP_query(), query_posts() and pre_get_posts

  3. with a background in relational database development, what I needed was a guide to SQL. I finally found one I could relate to allowing me to understand the utility of $wpdb.

    it would appear that using $wpdb is preferable to WP_Query if one is familiar with relational database design and SQL, and wants to keep database access as efficient as possible as long as one adheres to the safety precautions regarding data validation/preparation.

    I’ll play around with the $wpdb class/functions and move forward from there.