cancel
Showing results for 
Search instead for 
Did you mean: 

magento 2 get product category id value

magento 2 get product category id value

i have the following constuctor

class MagentoConnector {

protected $_userData = [];
protected $_password, $_url, $_token, $_sku;

public function __construct($u, $p, $url) {
$this->_url = $url;
$this->_userData = ["username" => $u, "password" => $p];
$this->getTokenInit();
}
what do i need to add in order to get the product category id value??

i am using rest to get the data example:

public function getProductName($sku) {
$ch = curl_init($this->_url . "V1/products/" . $sku);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . $this->_token));
$result = curl_exec($ch);
$result = json_decode($result);
if (!isset($result->message)) {
return $result;
}
1 REPLY 1

Re: magento 2 get product category id value

In case of GET "/rest/V1/products/{sku}" endpoint, in response you should see something like this:

{
  "id": 9,
  "sku": "24-WB02",
  "name": "Compete Track Tote",
  ...
  "extension_attributes": {
    "website_ids": [
      1
    ],
    "category_links": [
      {
        "position": 0,
        "category_id": "3"
      },
      {
        "position": 0,
        "category_id": "4"
      }
    ]
  },
  "product_links": [],
  "options": [],
  "media_gallery_entries": [ ],
  "tier_prices": [],
  "custom_attributes": []
}

So you need just decode response and check [extension_attributes][category_links] list.