Home › Forums › Backend Issues (wp-admin) › Dynamically populate relationship field
Hello,
I am trying to dynamically populate a relationship field (in a custom taxonomy) with all custom posts that have the current term.
I have been able to limit the post selection base on taxonomy with
Now I am trying to use acf/load_field whit a wp_query in order to get fields but I am not managing.
$field['choices'] = array();
// Required to make use of the wpdb Class
global $wpdb;
// Query the database
$the_query = new WP_Query(array(
'post_type' => 'article',
'posts_per_page' => -1,
'meta_key' => 'number_article',
'orderby' => 'meta_value',
'order' => 'ASC',
'tax_query' => array(
array(
'taxonomy' => 'issue_tax',
'field' => 'slug',
'terms' => array ('5')
)
)
));
if( $the_query->have_posts() ){
while( $the_query->have_posts() ){ $the_query->the_post();
$value = get_the_ID();
$label = get_the_title();
$field['choices'][ $value ] = $label;
}
}
return $field;
Any help?
Thanks
You cannot modify the choices of a relationship field by using a load field filter. These can really only be modified by using the method you mentioned https://www.advancedcustomfields.com/resources/acf-fields-relationship-query/
On a taxonomy page, or any page, ACF sends the current post ID as part of the request. I just did a test and here is what is in the $_POST array for the request.
Array
(
[paged] => 1
[taxonomy] =>
[post_type] =>
[s] =>
[max] =>
[min] =>
[action] => acf/fields/relationship/query
[field_key] => field_587ba38bc815c
[post_id] => category_4
[nonce] => b12e5fd166
)
In your acf/fields/relationship/query filter you can look at the post_id
value. From this you can get the taxonomy and the term ID. You can then use these values to modify the query args you return from your filter so that only posts in the current term are returned.
You know, now that I’m thinking about it, ACF passes $post_id to your filter and it more than likely has the same value, so you should just need to look at that value and alter the query args based on that.
The topic ‘Dynamically populate relationship field’ is closed to new replies.
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.