Home › Forums › General Issues › Hide values that have been selected in other post › Reply To: Hide values that have been selected in other post
https://www.advancedcustomfields.com/resources/acf-fields-relationship-query/
This could very likely time out the field and stop it from showing results.
The only way that I can thing to do this (well, the only way without querying the db directly) is to build a filter as suggested by @csaborio and in the filter get all other posts of the same time and look at what’s already been selected.
add_filter('acf/fields/relationship/query/name=related_tracks', 'remove_already_selected', 10, 3);
function remove_already_selected($args, $field, $post_id) {
$query = new WP_Query(array(
'post_type' => 'album', // my assumption
'post_status' => 'publish',
'posts_per_page' => -1
));
$selected = array();
if (count($query->posts)) {
foreach ($query->posts as $post) {
$tracks = get_field('related_tracks', $post->ID, false);
if (!empty($tracks)) {
foreach ($tracks as $track) {
$track = intval($track);
if ($track && !in_array($track, $selected) {
$selected[] = $track;
}
} // end foreach track
} // end if tracks
} // end foreach post
} // end if posts
if (!empty($selected)) {
$args['post__not_in'] = $selected ;
}
return $args;
} // end function
As I said, depending on the number of “Album” posts that exist this will eventually time out the AJAX request for the relationship field and would not be very scale-able.
You could potentially query the post meta table directly to get the acf field value for published posts.
Another possibility would be to create and acf/save_post. In this filter, when saving an “Album” post you could set an option (get_option()/update_option()) and store a list of selected tracks.
Yet another option would be to make the relationship bidirectional with a relationship on the Album side and a post object field on the track site. Then you could do something like this.
add_filter('acf/fields/relationship/query/name=related_tracks', 'remove_already_selected', 10, 3);
function remove_already_selected($args, $field, $post_id) {
$args['meta_query'] = array(
'relation' => 'OR'
array(
'key' => 'bidirectional_post_object_field_name',
'value' => ''
),
array(
'key' => 'bidirectional_post_object_field_name',
'compare' => 'NOT EXISTS'
)
);
return $args;
} // end function
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!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.