Opened 10 years ago
Closed 10 years ago
#31112 closed defect (bug) (invalid)
WP_Query fields=>ids parameter sometimes returns post objects instead of array of post IDs
Reported by: | lisota | Owned by: | |
---|---|---|---|
Milestone: | Priority: | normal | |
Severity: | normal | Version: | 4.1 |
Component: | Query | Keywords: | |
Focuses: | Cc: |
Description
I am trying to return an array of post IDs from a custom WP_Query. Simple queries like this seem to work fine:
$args = array( 'post_type" => 'sponsor_post', 'fields' => 'ids' ); $query = new WP_Query($args);
That successfully returns a list of post IDs for my custom post type called "sponsor_post".
Now add a meta_query to the parameter like so:
$args = array( 'post_type' => 'sponsor_post', 'meta_query' => array( array( 'key' => 'sponsor_post_type', 'value' => 'advertorial', 'compare' => '!=' ), ), 'fields' => 'ids' ); $query = new WP_Query($args);
Now the query returns an array of post objects, despite the fact that I've set the return parameter to 'fields' => 'ids'
How can I get WP_Query to respect the settings of the return fields parameter?
Change History (4)
#2
@
10 years ago
The SQL generated on mine was the same
SELECT SQL_CALC_FOUND_ROWS gw_wp_posts.ID FROM gw_wp_posts INNER JOIN gw_wp_postmeta ON ( gw_wp_posts.ID = gw_wp_postmeta.post_id ) WHERE 1=1 AND gw_wp_posts.post_type = 'sponsor_post' AND (gw_wp_posts.post_status = 'publish' OR gw_wp_posts.post_status = 'private') AND ( \n ( gw_wp_postmeta.meta_key = 'sponsor_post_type' AND CAST(gw_wp_postmeta.meta_value AS CHAR) != 'advertorial' )\n) GROUP BY gw_wp_posts.ID ORDER BY gw_wp_posts.post_date DESC LIMIT 0, 25
The problem was in the value returned. (WP_Query Object versus an array of post IDs) Let me try this same query in a staging environment and see if that makes a difference.
#3
follow-up:
↓ 4
@
10 years ago
OK. I figured this out. I wasn't paying enough attention to the query results, and some var_dumps helped me out. I was expecting the return to be an array of post IDs, and nothing else, based on the verbiage in the codex. There is an array of post IDs, but you have to get to it from the query object with $query->posts. Kind of a stupid mistake on my part.
I did find that the post IDs are strings and are not being cast to integers, which is odd since #27252 was supposed to fix it.
Hi lisota, thanks for the report.
I could not reproduce this on a clean install. This is the SQL query generated by the second snippet:
As you can see, it still selects post IDs.
Does the issue still happen with all plugins disabled and a default theme (Twenty Fifteen or Twenty Fourteen) activated?