1
votes

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.

1
I don't think 'key' => 'email', 'value' => $subscriber_email, is doing what you think it's doing... keep in mind, args is filtering the loop and there is't really anything in the posts themselves that would be filterable by this sort of logic. Let me ask you this: what if you removed the meta query altogether. Does the query work now? If so, what is it not doing? What are you trying to accomplish with subscribers as a post type? Why not use WP User Query?Evan Volgas
Nathan already gave me the clue of right direction.Ksenia

1 Answers

2
votes

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.