1

I've faced the problem while coding my very first prestashop template. So what I want to do is to get the list of all sub categories which are under the same parent category. So running foreach loop I need to send parent category id. In the internet there's not so much information about prestas' coding, modules or stuff, but I found two possible solutions. One was: {$product->id_category_default} but that works only inside a product page (?) Maybe I'm wrong and it's possible to get a solution with this? Another way sounds bit desperate: {$cookie->last_visited_category} problem with this one, that it works only if you come from parent category directly, but fails when followed by direct link or any other way. Also I was thinking of writing php function, which sends MySQL query and returns parent category id, but is this optimal way to do? Also I haven't tried writing my own php functions in smarty, seems it woks in some different way than just calling function.

So to conclude, do anyone knows how to get parent category id without separate php function and if it's so desperate, where and how to define your own php functions for smarty and how to call them.

I'm working with prestashop 1.4.

Thank you for your attention.

2
  • 1
    It depends on where you need that, to know which controller you need to modify. Is it for a module, or in what page do you need it? May 28, 2012 at 23:12
  • yeah sorry maybe I forgot to mention, I want this in category page, if is in subcategory, then I want to get parent category id May 29, 2012 at 9:42

1 Answer 1

3

I've used this code in a module, you might need to adapt it but basically, the id of the parent category is stored in the database.

$parentCategoryList = array(2, 3, 4, 5);
if(!in_array($id_category, $parentCategoryList)){
    $parentCategory = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
        SELECT DISTINCT c.id_parent
        FROM '._DB_PREFIX_.'category c
        WHERE c.id_category = '.(int)($id_category)
    );
    $id_category_parent = $parentCategory[0]['id_parent'];
}
else{
    $id_category_parent = $id_category;
}

In my code, the $parentCategoryList stores the id of my main categories (change it to your values). Then it checks if the category you're viewing ($id_category) is a main category. If not, it looks for the parent category in the database.

I am not really happy about the use of an array to store manually the main categories, but it works.

Hope this helps!

1
  • How to add this code to smarty code in header.tpl template file of my theme? May 13, 2014 at 6:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.