Home Forums Backend Issues (wp-admin) Dynamically populate Select Field with JSON


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 = '';
        $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. 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.

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Dynamically populate Select Field with JSON’ is closed to new replies.