0

I'd like to retrieve the post_id from wp_post_meta with a unique meta_key and meta_value. I've tried WP_Query but no values are returned and I'm unable to retrieve the post_id'

$post_query = new WP_Query( array(
    'meta_key' => 'key',
    'meta_value' => 'value',
    'fields' => 'ids',
) );

$post_ids = wp_list_pluck( $post_query->posts, 'ID' );

return $post_ids;

A similar post on Stackoverflow suggests that the only way is using a SQL query which differs to the suggestion from Sally CJ.

Using a SQL query returns the post_id. If possible, I'd like to use WP_Query or a native function if there's one.

1

1 Answer 1

1

Why are you using wp_list_pluck? In your query, you use 'fields' => 'ids' so the return is an array of found post ids.

From the codex:

'ids' – Return an array of post IDs.

Try returning $post_query->posts;

3
  • It only returns an empty array i.e. array(0) { }
    – Ryan
    Commented May 14, 2023 at 0:12
  • Then your key or value are wrong or do not exist in the database.
    – shanebp
    Commented May 14, 2023 at 0:38
  • the key and value match the strings in the database like for like.
    – Ryan
    Commented May 14, 2023 at 2: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.