Home › Forums › Add-ons › Repeater Field › Querying a repater field where a value is NOT inside any repater-entry › Reply To: Querying a repater field where a value is NOT inside any repater-entry
Okay, here is something I found out, which is working for my use case and might be helpful as a starting point for someone in the future. There might be better and more elegant ways to do this, but at least it does the trick in some cases.
Background: I use a post_relation field (among other) inside a repeater field and want to query all posts, which do not have a relation to one or more given post ids. As an example: I query posts of a post_type ‘recipe’ and want to get all posts (=recipes) which dont have a relation to some ingredients (‘ingredient’ is a post_type as well). The repeater field is named ‘ingredients’ and the relation field inside the repeater is called ‘ingredient’.
I build my wp_query step by step: standard query_args, meta_query_args and so on. Then I have an array of unwanted recipes. If this array is set (has values) I build a subquery and simply attach it at the end of the where clause (maybe not the best spot in regards to performance?). All of this happens in a closure (also, maybe not the best way to do this?).
if ( isset( $without_ingredients ) ) {
add_filter ('posts_where', function($where) use ($without_ingredients) {
global $wpdb;
$sql_in_no_repeater_extension = " AND $wpdb->prefix" . "posts.ID NOT IN (SELECT post_id FROM $wpdb->prefix" . "postmeta WHERE meta_key LIKE 'ingredients_%_ingredient' AND meta_value in (" . implode (',', $without_ingredients). "))";
return $where . $sql_in_no_repeater_extension;
});
}
What the simple subquery does, is getting the post id of all posts, having one of the uwanted post (ingredient) ids inside their ‘ingredients’-repeater subfields. Then these ids get removed from the original query.
So, maybe this helps someone sometime. If anyone has a hint how to do this better, I’d realy appreciate to read them.
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.