I have a Repeater field of Post Objects (here, a custom post type Participants) and I’d like a Relationship field’s options to be populated based on the Post Objects that were selected. I created a stand-alone function with an SQL query which works perfectly using $wpdb->get_results(), but I can’t figure out how to convert it into the WP_Query required by a Relationship field, or if there’s a way to simply feed the Relationship field the options I need directly.
Here’s the SQL that correctly gets my required data directly:
function get_class_participants($class_id){
global $wpdb;
$results = $wpdb->get_results(
"SELECT *
FROM <code>wp_postmeta</code> m
JOIN wp_posts part ON part.ID = m.meta_value
WHERE part.ID = m.meta_value
AND m.meta_key LIKE 'participants_%_participant'
AND m.post_id = '$class_id'
AND post_type = 'participant'
AND post_status = 'publish'
") or die(mysql_error());
return $results;
}
And here’s what I have so far using the acf/query filter (It doesn’t work):
add_filter( 'acf/fields/relationship/query/key=field_53d35e7b7908b', 'acf_participation_participants_meta_query');
function acf_participation_participants_meta_query( $args, $field, $post ) {
$args['meta_query'] = array(
array(
'key' => 'participants_%_participant',
'value' => '<code>wp_posts</code>.<code>ID</code>',
'compare' => '='
)
);
return $args;
}
This was also needed to get the post_query to search LIKE meta_key.
add_filter( 'posts_where', 'acf_repeater_dynamic_where', 10, 2 );
function acf_repeater_dynamic_where( $where, &$wp_query ){
if( !empty( $wp_query->meta_query->queries ) ){
$keys = wp_list_pluck( $wp_query->meta_query->queries, "key" );
foreach( $keys as $key ){
if( strpos( $key, '%') !== false ){
// custom filter to replace '=' with 'LIKE' for key
$where = str_replace("meta_key = '{$key}'", "meta_key LIKE '{$key}'", $where);
}
}
}
return $where;
}