Using custom sql query in wp_query function

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

Published by

Purab

I am Purab from India, Software development is my profession and teaching is my passion. Programmers blog dedicated to the JAVA, Python, PHP, DevOps and Opensource Frameworks. Purab's Github Repo Youtube Chanel Video Tutorials Connect to on LinkedIn

3 thoughts on “Using custom sql query in wp_query function”

  1. So this is returning an entire HTML webpage for me via my AJAX call. I’m also aiming to make a standard JSON call with an SQL query like this. Any advice would be appreciated.

Leave a Reply

Your email address will not be published.