Ksenia
Ksenia

Reputation: 173

WP_Query doesn't work with meta data fields

I have a custom post type 'subscribers'. And Subscribers have a meta field called 'email'. Emails are populated with subscribers emails. I need to get Subscriber ID only knowing the value of email field. So I try using this wp_query:

$args = array (
        'post_type' => 'subscribers',
        'meta_query' => array(
            array(
                'key' => 'email',
                'value' => $subscriber_email,
                'compare' => '=',
                'type' => 'CHAR',
            ),
        ),
    );

 $subscribers = new WP_Query($args);
 if ( $subscribers->have_posts() ) {
while ( $subscribers->have_posts() ) { 
         echo 'Found post!';
     }
  }
  else {
echo 'no posts found';
  } 

But only gives me 'no posts found' all the time. Also, I'm a bit confused about meta_key and meta_value. In Codex examples they use meta_key and meta_value in wp_query. But when I look on my mysql database postmeta table I see that meta_key field has value '_subscriber' and meta_value field has value a:1:{s:5:"email";s:16:"[email protected]";} What I'm doing wrong?

UPDATE: After advice of Nathan I rewrite the code and it did the job:

$args = array (
        'post_type' => 'subscribers',
        'meta_query' => array(
            array(
                'key' => '_subscriber',
                'value' => $subscriber_email,
                'compare' => 'LIKE'

            )
        )
    );

Though I decided to refactor my code and make all custom meta fields into strings, not serialized arrays. Because I'd like to use wp_query power to it's fullest in future.

Upvotes: 2

Views: 2338

Answers (1)

Nathan Dawson
Nathan Dawson

Reputation: 19308

The last part of your question is interesting and it's also why you have a problem.

Your meta key is '_subscriber'. You would therefore need to replace 'email' with '_subscriber' in the query.

The issue you have is your meta value. What you're seeing is a serialized array. You need to change the way this data is saved so that the value is a regular string.

Upvotes: 2

Related Questions