Support » Fixing WordPress » Filter by multiple custom fields in the loop

Viewing 3 replies - 1 through 3 (of 3 total)
  • You are correct in thinking that you are joining to only one row in the wp_postmeta table. You must join to the wp_postmeta table twice (this is UNTESTED – watch for typos):

    function filter_join($join) {
       global $wpdb;
       $join .= " JOIN $wpdb->postmeta pm1 ON ($wpdb->posts.ID = pm1.post_id)
       JOIN $wpdb->postmeta pm2 ON ($wpdb->posts.ID = pm2.post_id)";
       return $join;
    function filter_where($where) {
       $where .= " AND pm1.meta_key = 'gender' AND pm1.meta_value = 'male'
                   AND pm2.meta_key = '???'  AND pm2.meta_value = '???'";
       return $where;


    I didn’t realise you could link to the same table more than once, although seeing this example, giving it a different alias when you relink, it seems obvious!

    Is there a maximum number of times you can/should do this?


    MySql probably imposes a limit, but I do not know what it is. I am more familiar with Sybase which (used to, at least) limit you to 16 total tables in a query. EDIT: MySql limits you to 61 JOINS in a query.

    However, you will probably run into severe performance problems before you get anywhere near the limit. Again, Sybase used to quit trying to optimize a query at 5 tables so performance dropped dramatically at that point.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Filter by multiple custom fields in the loop’ is closed to new replies.