0

I have next code:

$drivers_all = $wpdb->get_results("SELECT DISTINCT meta_value FROM wp_postmeta WHERE meta_key = 'driver'")

With this one I get the values of all fields “driver”. How can I exclude some category in this code?

  • Do you really want to hard-code 'Driver' in there? There must be a better way to do this using the standard search. But to continue your SQL example you should AND NOT EXISTS a sub-query that matches the wp_postmeta post_id against wp_term_relationships, then using wp_terms and wp_term_taxonomy to find the taxonomy ID for your category. But you ought to do this properly with the standard query objects, not hard-code wp_ as the table prefix, etc. - this isn't the answer. – Rup Apr 25 '16 at 16:42
  • I need to count all unique values of “driver” except one category. By this time I’ve found only this part of solution – Bphoenix Apr 25 '16 at 16:55
0

I'm sure there's a better approach, but this query should do what you want:

SELECT DISTINCT meta_value FROM wp_postmeta pm
  WHERE meta_key = 'Driver'
    AND NOT EXISTS (SELECT * FROM wp_term_relationships tr
                      JOIN wp_term_taxonomy tt ON tt.term_taxonomy_id = tr.term_taxonomy_id
                      JOIN wp_terms t ON t.term_id = tt.term_id
                    WHERE pm.post_id = tr.object_id
                      AND tt.taxonomy = 'category'
                      AND t.name = 'ExcludeMeCategory');

When translating this into php you should use the $wpdb aliases for table names, i.e. $wpdb->postmeta, $wpdb->term_relationships, $wpdb->term_taxonomy, $wpdb->terms. You should also probably profile this query to make sure it's executing in reasonable time and isn't doing full table scans, etc. - I don't a representative database handy to test it.

Finally I don't know taxonomies well: this may be incomplete w.r.t. e.g. taxonomy hierarchies, and it may be simpler / better to query the taxonomy ID first and then drop that into the query in place of wp_terms_taxonomy onwards in the query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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