Support Forum
Support › MB User Meta › What's the quickest way to get users by term id?Resolved
Hi,
I have attached a taxonomy as user meta using the 'Taxonomy Advanced' field.
Now, when I go to the archive page for the term, I want to list all users with that term attached to their usermeta.
Using MB Views, I have tried the following:
{% set users = mb.get_users({
meta_query : {
meta_key: 'the_custom_taxonomy',
meta_value: term.id,
meta_compare: 'LIKE',
}
})%}
This returns all users but none seem to have the_custom_taxonomy field in the metadata. I have also tried get_users without the 'meta_query' wrapper array and the same result.
If I get all users first with get_users(), then I can do
{% for user in users %}
{% set umeta = mb.rwmb_meta ('the_custom_taxonomy', {object_type: 'user'}, user.ID) %}
{% endfor %}
but I'd prefer to query directly for users with the term.id.
What is the best way to do this?
EDIT:
The top query I put in DOES work with a bit of modification:
{% set users = mb.get_users({
meta_key: 'the_custom_taxonomy',
meta_value: term.id,
meta_compare: 'LIKE',
})%}
BUT, if the term.id I'm looking for is '4', it also returns term ids LIKE that, ie, '44', '104' etc.
So, I guess now my question is how to search for exact values in serialized arrays...
I have tried meta_compare 'IN' and '=' and they return 0 results....
Hi,
If you assign the location to the taxonomy archive, term.id
will return the current term ID on its page. So you can set the setting meta_compare
to =
{% set users = mb.get_users({
meta_key: 'the_custom_taxonomy',
meta_value: term.id,
meta_compare: '=',
})%}
Hi,
Thanks for the response.
If I set meta_compare to '=', I get no results... I already have the term.id I need (as this is all being generated in a view for archive pages).
As the taxonomy is hierarchical and is being chosen via a taxonomy_advanced UI in the user profile, doesn't MB save this as a serialized array in the DB? So for meta_compare: '=' to work, wouldn't I need to know the full serialized array, rather then one value within it?
Either way, meta_compare: '=' is definitely giving me no results.
Hi,
Thank you for your additional information.
If you use the cloneable
or multiple
setting, the taxonomy_advanced
field saved multiple term IDs or a serialized array in a single row in the database. But as far as I know, meta queries of WordPress support comparing the meta (field) value with the given value, not vice versa.
That means you can select one taxonomy and compare it with a given value like this
{% set users = mb.get_users({
meta_key: 'the_custom_taxonomy',
meta_value: [4, 5, 6], //given value
meta_compare: 'IN',
})%}
So I think you need to get all users and meta then compare it with the current term ID and print out the user matched.
Thanks again Long,
Yes that's what I had to do in the end: get all users first, get the metadata attached to all users, then extract the users with the specified term.id.
It seems that is the quickest (only) way