Search code examples
twigopencartopencart-3

Opencart 3.x category id in product page


I'm using opencart 3.0.2.0

I'm trying to get category id in the product page.

Any suggestions ?


Solution

  • If you just want to get category id in the product page

    Open product.php file from catalog/controller/product

    and search for

    $product_info = $this->model_catalog_product->getProduct($product_id);
    

    replace it with

    $product_info = $this->model_catalog_product->getProduct($product_id);
            $query_categories = $this->model_catalog_product->getCategories($product_id);
    
            $categories = array();
    
            foreach ($query_categories as $cat) {
                $ocb_category = $this->model_catalog_category->getCategory($cat['category_id']);
    
                $category_info['category_id'] = $ocb_category['category_id'];
                $category_info['name'] = $ocb_category['name'];
                $data['categories'][] = $category_info; 
            }
    

    open your product.twig file

    paste this code in it

    {% if (categories) %} 
        {% for category in categories %} 
            {% if category.category_id %} 
               <a>{{category.name}}:{{category.category_id}}<a><br>
            {% endif %} 
        {% endfor %} 
    {% endif %}
    

    Result: Category_name:Category_id (i.e. Electronics:223)

    Note: If the product is in multiple categories it will print all the categories with their ids

    Hope this might help you