0

I have this code on a Woocommerce site, which successfully returns the entire responded object:

function checkProducts($data) {
    $product_ID = $data['id'];
    $api_response = wp_remote_post( 'https://whatever.net/wc-api/v3/products/'.$product_ID, array(
        'method'    => 'GET',
        'headers' => array(
        'Authorization' => 'Basic ' . base64_encode( 'key:secret' )
        )
    ) );

    $body = json_decode( $api_response['body'] );

    if( wp_remote_retrieve_response_message( $api_response ) === 'OK' ) {
        return $body;
    }
}

I have tried to only return the stock_quantity property in many ways, which is present on the object, with no success, among others:

$body = json_decode( $api_response['body']['stock_quantity'] );
return $body['stock_quantity']:
return $body.stock_quantity;

JSON returned:

{
product: {
id: 687,
created_at: "2019-10-08T10:21:57Z",
updated_at: "2019-10-08T13:53:32Z",
type: "simple",
status: "publish",
downloadable: false,
virtual: false,
permalink: "https://germanalvarez.net/develop/ww/producto/tww-fin-de-semana-del-3-al-4/",
sku: "",
price: "200",
stock_quantity: "200",
sale_price: "120",
...

How could I archive this? Thank you

Biomehanika
  • 1,530
  • 1
  • 17
  • 45
  • 4
    What does `var_dump($body);` give you? Sounds like `$body->stock_quantity` should work but impossible to tell without seeing the data structure – Brett Gregson Oct 08 '19 at 14:25
  • Also, what are the _many ways_ and did it generate an error/notice? – AbraCadaver Oct 08 '19 at 14:28
  • Did you just skip over @BrettGregson comment? – AbraCadaver Oct 08 '19 at 14:33
  • I have just added your info and I am looking for the response for @BrettGregson, would you please give me a minute? Thank you. – Biomehanika Oct 08 '19 at 14:36
  • @BrettGregson, tried your example with no success, just returns null. I am facing problems with the var_dump() as I can not see it's result, I am quite unexperienced with this, sorry. I have edited adding final JSON that is returned to front – Biomehanika Oct 08 '19 at 14:51
  • Thanks for the mark @AbraCadaver, just learned how to do this. – Biomehanika Oct 08 '19 at 14:57

1 Answers1

0

First of all - json_decode will return an object by default: https://www.php.net/manual/en/function.json-decode.php

Try the following:

$body = json_decode( $api_response['body'] );
$stock_quantity = $body->product->stock_quantity;
return $stock_quantity;


If however you want to operate on an array, here's the way to do it (notice second parameter in json_decode):

$body = json_decode( $api_response['body'], true );
$stock_quantity = $body['product']['stock_quantity'];
return $stock_quantity;
Lukasz Formela
  • 447
  • 4
  • 17