[PHP] Get product category

  • Posts: 32
  • Thank you received: 5
1 year 3 months ago #353988

-- HikaShop version -- : 4.7.3
-- Joomla version -- : 4.3.3
-- PHP version -- : 7.4.33
-- Browser(s) name and version -- : Firefox 115.0.2 (64-bit)

Hi,

I have PHP code that runs everytime an order is created - onAfterOrderCreate($order). I want to access the value "category_parent_id". My code so far:

$productClass = hikashop_get('class.product');
$categoryClass = hikashop_get('class.category');

foreach ($order->cart->full_products as $product) {
$productAlt = $productClass->get($product->product_id);
$category = $categoryClass->get($productAlt->product_category_id);
echo $category->category_parent_id;
}

This fails, because the value in bold doesn't seem to exist. Yet if I read the HikaShop database model correctly, it should.

What am I doing wrong?

Attachments:

Please Log in or Create an account to join the conversation.

  • Posts: 82863
  • Thank you received: 13372
  • MODERATOR
1 year 3 months ago #353999

Hi,

No. The product_category_id column is in the hikashop_product_category table.
But the get function of class.product only loads the data in the hikashop_product table which doesn't contain that column.
So it's normal this doesn't work.
You can do it like this:

$productClass = hikashop_get('class.product');
foreach ($order->cart->full_products as $product) {
$categories = $productClass->getCategories($product->product_id);
foreach($categories as $category_id) {
 echo $category_id;
}
}
Note that one product can be linked to several categories.

The following user(s) said Thank You: NTV

Please Log in or Create an account to join the conversation.

  • Posts: 32
  • Thank you received: 5
1 year 3 months ago #354080

Hi nicolas,

I got it working like a charm. All I needed to add to your code is getting the actual category object via this line of code:

$category = $categoryClass->get($category_id);

Then I was able to access the parent category:

echo $category->category_parent_id;

Case Closed!

The following user(s) said Thank You: nicolas

Please Log in or Create an account to join the conversation.

Time to create page: 0.061 seconds
Powered by Kunena Forum