Get the exact SQL query that get_posts() generated
Question
I am working on a WordPress that someone else started and then disappeared. She created a few custom content types and variables using different plugins and I now want to access the data sets in the functions she created for her template.
$args = array(
'suppress_filters' => 0,
'posts_per_page' => -1,
'sort_order' => 'ASC',
'sort_column' => 'post_title',
'post_type' => 'inst',
'post_status' => 'publish'
);
$content = get_posts($args);
I have been looking around and different findings suggested using the following variable to get the SQL used:
echo $GLOBALS['wp_query']->request;
However, what this returns is not the query that shows the post data appearing on the page. When I run that in MySQL directly, it returns exactly 1 result and I think it's the whole page? Because I defined two datasets and there are two fields appearing on the page but only 1 row in the query that's echoed by above line.
I need to know the exact attributes of the WP_Query
object in $content but var_dump($content)
also doesn't contain the fields I defined. I need to get the image that's in the content typeset, but I can only get the name of the set accessing $content->post_title
.
Is there a way to dig into what get_posts()
gets from the database and how I can access the attributes I need?
Solution
The get_posts()
function creates an instance of WP_Query inside the function and simply returns the array of results. This WP_Query instance doesn't override the global $wp_query
and is out of scope by the time you need it. In short, I don't see a way how you can get the requested SQL via get_posts()
.
An alternative is to simply create your own instance of WP_Query and pass your get_posts()
arguments to it:
$query = new WP_Query( array(
'post_type' => 'inst',
'post_status' => 'publish'
'posts_per_page' => -1,
'order' => 'ASC', // sort_order
'orderby' => 'post_title', // sort_column
) );
That will give you the whole WP_Query object where you can output the SQL:
$query_sql = $query->request;
Finally, if you're already creating a WP_Query you don't need the get_posts()
call at all at that point.
if( $query->have_posts() ) {
while( $query->have_posts() ) {
$query->the_post();
the_content();
}
// Reset the global $wp_query to what it was originally.
wp_reset_postdata();
}