Happy Halloween! Get 20% off GP Premium with the discount code: HALLOWEEN20

[Support request] Return an Empty Array in REST API Response

Home Forums Support Return an Empty Array in REST API Response

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
  • #933794

    I know this is well beyond the scope of GeneratePress, but hoped the community might have some insights that could help me solve an issue I’m having with a REST API reply and a custom field.

    In short I’ve created a custom REST API endpoint that serves data from a custom post type with ACF fields to a desktop application. The endpoint is working nicely except for one field when it has a blank value.

    Specifically, the ‘HostSoftwareSupportedVersions’ field returns an array whenever one or more options are selected (what I need). Conversely, an empty string is returned whenever no options are selected. Although most items have a value, an empty value is acceptable in this case.

    With that in mind, what I need is for WordPress to return an empty array, not string, if no option is selected. Below is the basic code I am working with. Again, the field I’m having trouble with is ‘HostSoftwareSupportedVersions’

    function dg_get_tools() {
      $args = array (
        'post_type' => 'tools',
        'post_status' => 'publish',
    	'posts_per_page' => -1,
      $items = array();
      if ( $posts = get_posts( $args ) ) {
        foreach ( $posts as $post ) {
          $items[] = array(
            'id' => $post->ID,
    		'ContentType' => implode(wp_get_post_terms( $post->ID, 'itemtype', array( 'fields' => 'ids' ) )),
    		'Name' => 'TEST ' .$post->post_title,
    		'LongDescription' => $post->post_excerpt,
    		'HostSoftware' => reset(get_post_meta($post->ID, 'software')),
    		'HostSoftwareSupportedVersions' => reset(get_post_meta($post->ID, 'software-version')),
    		'Url' =>  implode(get_post_meta($post->ID, 'item_url')),
      return $items;
    Lead Developer
    Lead Developer

    Hi there,

    I’m not sure what the reset() function does, but maybe try this instead?:

    'HostSoftwareSupportedVersions' => reset( (array) get_post_meta($post->ID, 'software-version')),

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.