I have a custom table called "tags" that contains a charity_id that is a reference to a post ID ... I need to query the "tags" table to grab this charity_id and then pull in the post title and a few of the meta data.

Ideally, the end result would produce the following:

tags.serial_number, post.title, post_meta_data.post_title, post_meta_data.location_city, post_meta_data.location_state, post_meta_data.location_country
  • Why do you want to use a custom MySQL query when the WordPress function get_post_custom($post_id) would do all the work for you once you have the $post_id. I am assuming your post_meta_data.* refers to data in the WordPress table and not a custom table of yours.
    – user27457
    Commented Aug 14, 2014 at 21:20

2 Answers 2


You have to use JOIN for that. Try it like this:

$wpdb->get_results("SELECT tags.*, $wpdb->posts.*, $wpdb->postmeta.*
              FROM tags
              INNER JOIN $wpdb->posts ON tags.charity_id = $wpdb->posts.ID
              INNER JOIN $wpdb->postmeta ON tags.charity_id = $wpdb->postmeta.post_id
              WHERE tags.charity_id = $charity_id"
  • @MagentaCuda You're right. I overlooked that. get_results() will solve that.
    – sakibmoon
    Commented Aug 14, 2014 at 21:51

Wpdb can solve the custom table problems. But tag.charity_id has to be foreign key of the charity.ID

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.