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?


3 Answers 3


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.


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

  • can't use next_post_link(). they don't allow one to specify a single category, something that most people mentioning these functions tend to ignore... although one could perhaps get all of the terms for the current post and exclude all of them except for the one needed... worth considering. btw, wp_query() is documentated here: codex.wordpress.org/Class_Reference/WP_Query
    – Gregory
    May 31, 2012 at 14:30
  • 1
    @Gregory pay attention that you made a mistake in your question: you wrote wp_query() - it is a function. But WP_Query is a class. It's big different. May 31, 2012 at 14:39
  • thank you for the clarification. still, does anyone know when one should use $wpdb as opposed to WP_Query ? I've done quite a few searches on the 'net but haven't found any answers, at least as far as queries go rather than updates/inserts/deletes.
    – Gregory
    Jun 1, 2012 at 3:25
  • @Gregory I have updated my answer, check it out. Jun 1, 2012 at 4:59

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.

  • 1
    That’s not answer, is it? You should update your question if you want to add further details.
    – fuxia
    Jun 4, 2012 at 16:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.