Using custom sql query in wp_query function

People asked me fetching data from wordpress database with simple database query. You can use get_results() method for custom sql query in wp_query function.

Using custom sql query in wp_query function

Is this facility provided by wordpress API. Yes, that is provided by wordpress api. You just need to use the get_results() method. Here I am going to give some example about using the custom sql query in wp_query method.

You need to define the gobal $wpdb variable that important in your code. here is working example for fetching the posts.


global $wpdb;

$querystr = "SELECT wp_posts.* FROM $wpdb->posts wp_posts, $wpdb->postmeta
WHERE wp_posts.post_status = 'publish' AND wp_posts.post_type = 'post'
ORDER BY wp_posts.post_date DESC LIMIT 10";
$pageposts = $wpdb->get_results($querystr, OBJECT);

For fetching the Admin or user information thorough query use following code. following code is useful for fetching the single record or row.


$querystr = "SELECT wp_users.* FROM $wpdb->users
WHERE wp_users.user_email = 'info@domain.com' ";
$userinfo = $wpdb->get_row($querystr);

For detail information you should use the following URL:

http://codex.wordpress.org/Function_Reference/wpdb_Class

Using custom sql query in wp_query function
Using custom sql query in wp_query function