WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a site with many users and many of them have the same last name. I want to get the emails of all the users with the same last name (IE: Smith) that has a post related to a particular taxonomy term (IE: Baseball).

So far I have this code that works great in getting all the users with the same last name ( thanks to Mike Schinkel ). I suck at using the JOIN function but I am learning and I really need this sooner than later, so I need help.

$sql =<<<SQL
  LEFT JOIN {$wpdb->usermeta} ON {$wpdb->users}.ID = {$wpdb->usermeta}.user_id
  AND {$wpdb->users}.user_status = '0'
  AND {$wpdb->usermeta}.meta_key = 'last_name'
  AND {$wpdb->usermeta}.meta_value = 'Smith'
  $usersemails = $wpdb->get_results($sql);

Your time is greatly appreciated and I will pay it forward. Thanks.

share|improve this question
up vote 1 down vote accepted

Hi @Holidaymaine:

Here's the query you are looking for:


include( '../wp-load.php' );

$sql =<<<SQL
  u.user_email AS user_email,
  um.meta_value AS user_lastname
  {$wpdb->users} AS u
  LEFT JOIN {$wpdb->usermeta} AS um ON u.ID = um.user_id
  LEFT JOIN {$wpdb->posts} AS p ON u.ID = p.post_author
  LEFT JOIN {$wpdb->term_relationships} AS tr ON p.ID = tr.object_id
  LEFT JOIN {$wpdb->term_taxonomy} AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  LEFT JOIN {$wpdb->terms} AS t ON tt.term_id = t.term_id
  AND u.user_status = '0'
  AND um.meta_key = 'last_name'
  AND um.meta_value = '%s'
  AND t.slug = '%s'
  $sql = $wpdb->prepare( $sql, 'Smith', 'baseball' );
  $usersemails = $wpdb->get_results( $sql );
  header( 'Content-type:text/plain' );
  print_r( $usersemails );
share|improve this answer
Thank you Mike. This is perfect and saved me a lot of time and headache. I can never repay you, but as promised I will pay it forward. Thanks again. – Holidaymaine Apr 23 '11 at 8:11
@Holidaymaine - Glad I could help. How to repay me (and others?) Just be sure to come here often, ask great questions, vote often for good answers (even for answers to questions you did not ask), and then remember to come back to select the best answers (as you did for this question.) – MikeSchinkel Apr 23 '11 at 20:26
No problem. Will do. – Holidaymaine Apr 24 '11 at 2:48

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.