Search code examples
phpwordpresswordpress-rest-api

Same response on internal call in for loop


I am using Wordpress as a backend and I am formatting some stored data for the application. I call in a for loop to aggregate the data but the response seems to be the same even though I am making sure the URL called is different.


  foreach ($data as $attr) {
      if (in_array(strtolower($attr['name']), $array)) {
            $list = $this->getAttributeTerms($attr['id']);
            $attributes[strtolower($attr['name'])] = $list;
      }
   }

/*...*/

  private function getAttributeTerms($attributeID)
    {
        $request = new WP_REST_Request('GET', '/wc/v3/products/attributes/' . $attributeID . '/terms');

        $resp = rest_get_server()->dispatch($request)->data;

        var_dump('/wc/v3/products/attributes/' . $attributeID . '/terms');
        var_dump($resp);

        return array_map(function ($val) {
            return ['id' => $val['id'], 'name' => $val['name']];
        },  $resp);
    }

The response is the value of the first called getAttributeTerms instead of being different each time, which wasn't what I expected to happen.


Solution

  • Instead of getting the attribute terms this way, which I now realize was a bit of an overkill I ended up using the get_terms function to return the data necessary.

    function slimTaxonomyData($el)
    {
        return ['id' => $el->term_id, 'name' => $el->name];
    }
    
    return [
       'taxA' => array_map('slimTaxonomyData', get_terms(['taxonomy' => 'tax_a_tag', 'orderby' => 'name'])),
       'taxB' => array_map('slimTaxonomyData', get_terms(['taxonomy' => 'tax_b_tag', 'orderby' => 'name'])),
    ];