2
\$\begingroup\$

In general, in prestashop there are no funcions to really have the final (the one with highest level_depth) category of a product based on id_product, so I extended the Product class and added this simple static method:

public static function get_product_category($id_product, $id_lang = null){
    $lang = (!isset($id_lang)) ? (int)Context::getContext()->language->id : $id_lang;

    $db = Db::getInstance();

    $sql = 'SELECT
                    c.id_category,
                    c.id_parent,
                    cl.name,
                    cl.link_rewrite

              FROM '._DB_PREFIX_.'category_product cp
              INNER JOIN '._DB_PREFIX_.'category c ON cp.id_category = c.id_category
              INNER JOIN '._DB_PREFIX_.'category_lang cl ON cl.id_category = c.id_category
              WHERE cp.id_product = ' . bqSQL($id_product) . ' and cl.id_lang = ' . bqSQL($lang) . '
              ORDER BY c.level_depth DESC
              LIMIT 1';

    $result = $db->ExecuteS($sql);

    return $result[0];
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.