Home › Forums › Backend Issues (wp-admin) › Dynamically populate Select Field with JSON
I’m wanting to dynamically populate a Select Field with JSON so that I can select a category of posts from an external site. My code is throwing a critical error though. Not sure what I’m overlooking. Do you have any ideas?
/**
* Filter Select Choices from Blog Categories
*/
function blog_CategoryQuery( $field ) {
// Declare empty array
$field['choices'] = array();
// Query with JSON
$source = 'https://blog.com/wp-json/wp/v2/categories';
$json = file_get_contents($source);
// Convert JSON to an array of posts
$blogPosts = json_decode($json);
if( is_array($blogPosts) ) {
// Call category ID and category name
foreach ($blogPosts as $blogPost) {
$value = $blogPost -> id;
$label = $blogPost -> name;
// Append category to choices
$field['choices'][$value] = $label;
}
// Return the field
return $field;
}
}
add_filter('acf/load_field/key=field_qwerty', 'blog_CategoryQuery');
This has nothing to do with your error. acf/load_field will work, but you should use acf/prepare_field to modify the choices. https://www.advancedcustomfields.com/resources/acf-prepare_field/. The reason for this is that when you use load_field the choices will by update and stored if you are using local json or you export the field group. When you use load_field you’re also running your filter in places it does not need to be run.
What is the critical error that’s being reported? That would help to figure out what’s wrong.
The only thing that I can see as in issue with your code is that
return $field;
is inside the if block. This means that of the results of
if( is_array($blogPosts) ) {
is not true then $field
well be set to NULL
because nothing is returned if the condition is false.
Thanks John, the critical error was something else. Have fixed everything with your comments. And it’s now working perfectly. Thank you so much. You’ve been a huge help.
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!
🚀 This week’s session of ACF Chat Fridays dips into the preliminary results of our first ever user survey. Don’t miss it! https://t.co/3UtvQbDwNm pic.twitter.com/kMwhaJTkZc
— Advanced Custom Fields (@wp_acf) May 9, 2023
© 2023 Advanced Custom Fields.
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 Cookie Policy. If you continue to use this site, you consent to our use of cookies.