I have created a custom field (office_name) that displays on the user form. Each user is then able to choose the appropriate office with a select field:
My goal is to create a query that matches all posts by each user that matches a specific office name. For example, if two users have “Office 1” selected, I would like to display all posts by those two users.
I can accomplish this easily by manually coding the user ID’s as below:
$office_listings = get_posts(array( 'author__in' => array(1,2,4,6), 'posts_per_page' => -1 )); if( $office_listings ): endif;
I’m hoping to find a dynamic way of doing this as to avoid having to manually update the code each time a new user is added to a specific office location.
I did try something like it shows in the Docs:
$posts = get_posts(array( 'numberposts' => -1, 'meta_key' => 'office_name', 'meta_value' => 'Office 1' ));
This did not work.
If anyone could help me out with this, it would be greatly appreciated.
There isn’t any way that you can do this with one query because you are adding locations to users. I’m not even sure you could do it in one query if you were adding users to locations.
Locations added to users
Users added to locations, this would be easier
Due to the way relationship fields are stored (this includes, relationship, taxonomy, user and any field that relates one WP object to another) as serialized arrays, and the fact that you can’t really query across multiple types of WP objects (multiple post types or users/post types) there isn’t going to be a way to do this with just a WP_Query and you’re going to need to do some kind of extra work and more than likely multiple queries to make it happen.
Hi John, after thinking through the information you provided, I was in fact able to come up with an easy solution:
$office_employees = get_users( array( 'meta_key' => 'office_name', 'meta_value' => 'Office 1', 'fields' => 'ID' )); $office_listings = get_posts(array( 'author__in' => $office_employees, 'posts_per_page' => -1 )); if( $office_listings ): endif;
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
The ACF site is currently experiencing some issues.— Advanced Custom Fields (@wp_acf) September 21, 2022
We apologize for the inconvenience and we are working hard to get it back up and running as soon as possible.
© 2022 Advanced Custom Fields.