OpenCart header navigation (three level list)

Recently, I had a bite of Open Cart to build a new website for a client. Its still in development, but the outcome seems promising. I have to say, as much as I had heard about Open Cart, it really is a great piece of web application. My journey with shopping carts have been restless. I have had tough times with OSCommerce, played enough with ZenCart, dealt with the terrible NiagaKit, and even adventured on my favorite enterprise level Magento. While Magento is still the best for me, Open Cart is just the next one for me. Reason why Open Cart is behind Magento is only because of the number of features that it has. For my carts that need enterprise love, I use Magento for them. For all others, Open Cart is my choice now.

So, I was modding a custom made theme for a client who will be selling products on his very own Open Cart. I realized that it did not have header navigation. Actually, it did not have category list tables. The current category.tpl template file calls the categories available for the viewed page only. While Open Cart will be implementing listed categories in the next version, my client couldn’t wait. So I had to do what I had to do.

Google! Thats where I found Craig Murrays neat category list code. The code works, but apparently he limited it to two level navigation only. The parent and a child. I think for a shopping cart, the maximum navigation levels should be three rather than two. In my clients case who was selling hijabs, she needed three level navigation. eg: hijab -> the type of hijab -> the material. So I took Craig’s code and modified it into a three-level navigation. The generated list item will look something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<ul>
   <li>First Level</li>
   <li>First Level
      <ul>
         <li>Second Level</li>
         <li>Second Level
            <ul>
               <li>Third Level</li>
               <li>Third Level</li>
            </ul>
         </li>
         <li>Second Level</li>
       </ul>
   </li>
   <li>First Level</li>
</ul>

Once you have this list, you can give it some CSS touch and use Superfish or most other jQuery scripts to add the animation effect for added functionality. Now here is the PHP code to generate this list (along with descriptions on what each line does):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?php 
 
$this->load->model('tool/seo_url');
 
$results = $this->model_catalog_category->getCategories();  									// get the categories
 
if ($results) {$output = '<ul class="you-can-define-a-class-here-for-your-javascripts">';}  									// if there are categories available, start off with the unordered list tag
 
foreach ($results as $result) {																	// for each result
	$output .= '<li>';																			// put a list item tag
	$new_path = $result['category_id'];															// get the id of this category
	$unrewritten = HTTP_SERVER.'index.php?route=product/category&path=' . $new_path;			// if the seo url is disabled, this will be the path
	$rewritten = $this->model_tool_seo_url->rewrite($unrewritten);								// otherwise, it will be this one
	$output .= '<a href="' . $rewritten . '">' . $result['name'] . '</a>';						// finally, generate the category name and wrap its link
 
	$sub_results = $this->model_catalog_category->getCategories($new_path);						// if this result has a sub-list, get the set of new categories
 
	if ($sub_results) {$output .= '<ul>';}														// if this is a subresult, start off with an unordered list tag
 
	foreach ($sub_results as $sub_result) {														// for each of this subresult item
		$output .= '<li>';																		// put a list item tag
		$new_sub_path = $sub_result['category_id'];												// get its category
		$sub_unrewritten = $unrewritten.'_'. $new_sub_path;										// if the seo is disabled, this will be the path
		$sub_rewritten = $this->model_tool_seo_url->rewrite($sub_unrewritten);					// otherwise, it will be this one
		$output .= '<a href="' . $sub_rewritten . '">' . $sub_result['name'] . '</a>';			// now, generate the category name and wrap its link
 
		$third_sub_results = $this->model_catalog_category->getCategories($new_sub_path);		// if this result has a sub-list, get the set of new categories
 
		if ($third_sub_results) {$output .= '<ul>';}											// if this is a subresult, start off with an unordered list tag
 
		foreach ($third_sub_results as $third_sub_result) {										// for each of this third level item
			$output .= '<li>';																	// give it an opening list tag
			$third_sub_path = $third_sub_result['category_id'];									// get its category
			$third_sub_unrewritten = $sub_unrewritten.'_'.$third_sub_path;						// if seo is disabled, this is the path
			$third_sub_rewritten = $this->model_tool_seo_url->rewrite($third_sub_unrewritten);	// if its enabled, this will be the path
			$output .= '<a href="'.$third_sub_rewritten.'">'.$third_sub_result['name'].'</a>';	// call the category name and wrap with its link
			$output .= '</li>';																	// now close this list item
		}
 
		if ($third_sub_results) {$output .= '</ul>';}											// if this was the third list, clost the list
			$output .= '</li>';																	// then or otherwise, close the second level list tag
	}
	if ($sub_results) {$output .= '</ul>';}														// if all sub results have been listed, close the second level
		$output .= '</li>';																		// then or otherwise close first list parent
}
if ($results) {$output .= '</ul>';}																// then close the first level list table
echo $output; 																					// now produce the results
?>

I hope that helps for some of you guys looking forward to add this to your Open Carts. Open Source..ftw!

Shahz

Print
  1. Patrick
    #1 written by Patrick  (6 years ago)

    Thanks! I really like your code but would like to add a feature:

    I’d like to assign a class to that li-tag which is active.
    Like:

    Could you help me out?

    Best, Patrick

  2. Shahz
    #2 written by Shahz  (6 years ago)

    Pretty simple if you ask me..If you want to assign the same class to every list item, change these lines:
    $output .= ‘< li >‘;
    to:
    $output .= ‘< li class="the-class-name" >‘;

    and if you want to assign dynamic classes to each of the list items, since each category has its own id, and since we are calling out each id using the $new_path variable, you can integrate the $new_path variable within the $output variable..

    Hope that helps :)

  3. Patrick
    #3 written by Patrick  (6 years ago)

    Oh thank you. But I only want to output the class “active” for that li-element which belongs to the current page/category.

    For example: If I have a category called “shoes”, I just want to add the class (to that particular li which contents the link to cat. “shoes”) if a page of that category (or subcat.) is displayed.

    Goal is to highlight the current/active category in the list-menue.

  4. George
    #6 written by George  (6 years ago)

    Works great! Thank you so much

  5. dominikus
    #7 written by dominikus  (6 years ago)

    thanks for sharing, I’m try to implemented ;)

  6. visitor
    #8 written by visitor  (6 years ago)

    thanks, nice work!!

  7. Tone
    #10 written by Tone (6 years ago)

    Works Great. Great Appreciation. How do i assign a class to only lists that are expanding again for ex:

    Example
    Example
    Example Expanding

    Example

    Example

    The reason is i want to be able to put an arrow Background to show theres more on that list.

    thanks

    • Shahz
      #11 written by Shahz  (6 years ago)

      Dependnig on your code, here is one way to do it:
      Replace:
      $output .= ‘‘;
      to:
      $output .= ‘‘;

      • Shahz
        #12 written by Shahz  (6 years ago)

        Ignore that..It didn’t post the html..lol..

        $output .= ‘‘;
        to:
        $output .= ‘‘;

        • Shahz
          #13 written by Shahz  (6 years ago)

          Ignore that too..Read the comment #2 up there..

  8. sijo thomas
    #14 written by sijo thomas  (5 years ago)

    when i put this code in header.tpl i’m getting this Error: Could not load model tool/seo_url!
    I’m using Open Cart v1.5.0.5….Any help will be appreciated….

  9. sijo thomas
    #15 written by sijo thomas  (5 years ago)

    ya its woking …..nice and great script…

  10. vishu
    #16 written by vishu  (5 years ago)


    sijo thomas:

    i’m also getting this Error: Could not load model tool/seo_url!
    I’m using Open Cart v1.5.0.5….Any help will be appreciated

    when i put this code in header.tpl i’m getting this Error: Could not load model tool/seo_url!
    I’m using Open Cart v1.5.0.5….Any help will be appreciated….

  11. Allen Conquest
    #17 written by Allen Conquest  (5 years ago)

    I think v1.5.x has changed the way is works. Look at information/sitemap.tpl to see how the categories are now retrieved.

    I’ve not tried it yet, but I think the line is: $this->load->model(‘catalog/category’);

  12. Allen Conquest
    #18 written by Allen Conquest  (5 years ago)

    Ok, I got it working using a few modification. It’s not doing the SEO rewrites, I’m not sure how to do that at the moment:

    //$this->load->model(‘tool/seo_url’);
    $this->load->model(‘catalog/category’);

    $results = $this->model_catalog_category->getCategories(0);

    if($results)
    {
    $output = ”;
    }

    $output .= ‘Home‘;

    $counter = 0;

    foreach ($results as $result)
    {
    // HTML
    $output .= ”;

    // Grab the specific category, reset each loop
    $new_path = $result[‘category_id’];

    // Prepare the URL
    $unrewritten = HTTP_SERVER.’index.php?route=product/category&path=’ . $new_path;

    // Pass it to the SEO URL tool
    // $rewritten = $this->model_tool_seo_url->rewrite($unrewritten);

    // Output the path and category name
    $output .= ‘‘ . $result[‘name’] . ‘‘;

    $counter++;

    // Next level deep with the current category as the parameter.
    // Children of
    $sub_results = $this->model_catalog_category->getCategories($new_path);

    // If there are subs
    if ($sub_results)
    {
    // HTML
    $output .= ”;
    }

    foreach ($sub_results as $sub_result)
    {
    // HTML
    $output .= ”;

    // Allocate the new sub category
    $new_sub_path = $sub_result[‘category_id’];

    // Get the raw URL and prepare it
    $sub_unrewritten = $unrewritten.’_’. $new_sub_path;

    // Rewrite it
    // $sub_rewritten = $this->model_tool_seo_url->rewrite($sub_unrewritten);

    // Output as usual
    $output .= ‘‘ . $sub_result[‘name’] . ‘‘;

    // Grab the specific category, reset each loop
    $new_sub_path = $sub_result[‘category_id’];

    // Next level deep with the current category as the parameter.
    // Children of
    $sub_sub_results = $this->model_catalog_category->getCategories($new_sub_path);

    // If there are subs
    if ($sub_sub_results)
    {
    // HTML
    $output .= ”;
    }
    else
    {
    $output .= ”;
    }

    $counter2 = 0;
    foreach ($sub_sub_results as $sub_sub_result)
    {
    // HTML
    $output .= ”;

    // Allocate the new sub category
    $new_sub_sub_path = $sub_sub_result[‘category_id’];

    // Get the raw URL and prepare it
    $sub_sub_unrewritten = $unrewritten.’_’. $new_sub_path.’_’.$new_sub_sub_path;

    // Rewrite it
    // $sub_rewritten = $this->model_tool_seo_url->rewrite($sub_unrewritten);

    // Rewrite it
    // $sub_sub_rewritten = $this->model_tool_seo_url->rewrite($sub_sub_unrewritten);

    // Output as usual
    $output .= ‘‘ . $sub_sub_result[‘name’] . ‘‘;
    $output .= ”;
    $counter2++;
    }

    if ($sub_sub_results)
    {
    // Close off children UL
    $output .= ”;
    }
    $output .= ”;
    }

    if ($sub_results)
    {
    // Close off children UL
    $output .= ”;
    }

    }

    if ($results)
    {
    // Close parent UL
    $output .= ”;
    }

    echo $output;

  13. Edmend
    #19 written by Edmend  (5 years ago)

    could you tell me which file i need to change? i using 1.5.1 opencart.

    Thank

  14. Imran
    #20 written by Imran  (5 years ago)

    Thanks………Good work…….its greate.

  15. Imran
    #21 written by Imran  (5 years ago)

    could you tell me which file i need to change? i using 1.5.1 opencart.

    Thank

    where u want to use drop down if header then header.tpl if anywhere else then that file…………

    regards……..
    Imran Manzoor

  16. Martin Vondracek
    #22 written by Martin Vondracek  (5 years ago)

    Hello guy, thanks a lot for this post. It’s verz usefull to me.

    Very good work. Thanks again :)

  17. tarang
    #23 written by tarang  (5 years ago)

    Hi shaaz,
    Thank you for this code..
    I need to implement it on new version of opencart i.e 1.5.3
    Are there any modifications required or will this code work?
    I am new to PHP and opencart both..really looking forward to your help..

  18. tarang
    #24 written by tarang  (5 years ago)

    Hello Shahz,

    Waiting for your response…any help would be appreciated..

  19. Wayne
    #25 written by Wayne  (5 years ago)

    Hi Shahz, this looks very straightforward but like tarang above I am new to both PHP and OpenCart and I need some advice on how to implement this. It looks very easy but I am not sure where to start. Please could you help us out or email (provided in form). Many thanks.

  20. Shahz
    #26 written by Shahz  (5 years ago)

    Sorry guys,

    This code is pretty old now. It was implemented for OpenCart before 1.5. I’ve yet to play with the new version.

  21. Wayne
    #28 written by Wayne  (5 years ago)

    Hi Shahz, thanks for the reply. I am using OpenCart 1.5 and really want this on the website! Please could you help? I would really appreciate it.

  22. tarang
    #29 written by tarang  (5 years ago)

    Hi Shahz,
    Thanks for replying. Like Wayne above, i also want it on my website and my product upload is pending due to this change..
    I have searched opencart forums and php forums..even posted a request to Craig Murray, but m not getting any help :(
    Really looking forward for your help…
    Thanks in advance..!!

  23. avriukas
    #30 written by avriukas  (5 years ago)

    it is so actual for me too..

  24. Goke
    #31 written by Goke (4 years ago)

    hello all,
    Can someone guide me on introducing the Shahz script in to version 1.5.4.1 of the opencart?
    I have tested even the online demo, the second sub menu is not working.

    Your guide is key please.

    Goke

  25. metal gear solid ground zeroes free giveaway

    We stumbled over here from a different website and thought I should check things out.
    I like what I see so now i’m following you. Look forward to looking
    into your web page repeatedly.

    my website; metal gear solid ground zeroes free giveaway

  26. farm heroes saga hack
    #33 written by farm heroes saga hack (3 years ago)

    Hi, this weekend is pleasant for me, because this point in time i
    am reading this fantastic informative piece of writing
    here at my house.

    Here is my blog: farm heroes saga hack

  27. game of war fire age hack
    #34 written by game of war fire age hack (3 years ago)

    Hi there I am so grateful I found your webpage, I really found
    you by accident, while I was looking on Yahoo for something else, Regardless I am here now and
    would just like to say thank you for a fantastic post and a all
    round enjoyable blog (I also love the theme/design), I don’t have time to read through it
    all at the minute but I have saved it and also added your
    RSS feeds, so when I have time I will be back to read more, Please do keep up the
    awesome job.

    My website game of war fire age hack

  28. Farm Heroes Saga Hack
    #35 written by Farm Heroes Saga Hack (3 years ago)

    So low was Lucas’s space-fantasy adventure held in regard by
    the “suits” at Fox that they asked theaters
    to screen it on the Wednesday before the Memorial Day Weekend
    if the movie house owners wanted to be able to exhibit the more “bankable” The Othe Side
    of Midnight. Puhvel, Jaan, Analecta Indoeuropaea, (a collection of articles), publ.

    Sivana called him “the Big Red Cheese” and the nickname stuck
    among both other villains and fans.

    my web page: Farm Heroes Saga Hack

  29. Www.agrisk.umn.edu
    #36 written by Www.agrisk.umn.edu  (3 years ago)

    A large amount of excellent information on this web site, really
    need a steam shower unit within my bathroom

    my blog post – steam shower benefits (http://Www.agrisk.umn.edu)

  30. Facebook Hack
    #37 written by Facebook Hack (3 years ago)

    Hi there, jujst became alert to your blog through
    Google, and found that it’s really informative.
    I’m going to watch out for brussels. I will alpreciate iif you
    continue this in future. Numerous people will be bnefited from your writing.
    Cheers!

  31. Formula T10 Testosterone Booster
    #38 written by Formula T10 Testosterone Booster (3 years ago)

    If you desire to get much from this post then you have to apply such methods to your won blog.

  32. vapor x electronic cigarette reviews
    #39 written by vapor x electronic cigarette reviews (3 years ago)

    Have you ever thought about creating an ebook or guest
    authoring on other blogs? I have a blog centered on
    the same information you discuss and would really like to have you
    share some stories/information. I know my viewers would enjoy your work.
    If you’re even remotely interested, feel free to send me an e-mail.

  33. baby name generator for girls
    #40 written by baby name generator for girls  (3 years ago)

    I think this is one of the most vital information for me.
    And i’m glad reading your article. But should remark on few general things, The web site style is wonderful, the articles
    is really excellent : D. Good job, cheers

  34. drupal
    #41 written by drupal  (3 years ago)

    With havin so much written content do you ever run into any issues of plagorism or copyright infringement?

    My site has a lot of unique content I’ve either created myself or outsourced but it seems a lot of it is popping it up all over the internet
    without my authorization. Do you know any techniques to help
    stop content from being ripped off? I’d definitely appreciate
    it.

  35. Ana
    #42 written by Ana (3 years ago)

    This post presents clear idea in favor of the new viewers of blogging, that genuinely how to do blogging.

    Feel free to visit my web-site :: toronto seo services (Ana)

  36. Corine
    #43 written by Corine (3 years ago)

    My spouse and I absolutely love your blog and fiund
    the majority of yoour post’s too be just what I’m looking for.
    Do you offer guest writers to write content in your case?
    I wouldn’t mind writing a post or elaborating on a lot of the subjects you write in relation to here.
    Again, awesome blog!

  37. best drum machine
    #44 written by best drum machine (3 years ago)

    you are actually a excellent webmaster. The site loading speed is amazing.

    It seems that you’re doing any unique trick. Furthermore, The contents are masterwork.
    you have performed a great task in this topic!

  38. news
    #45 written by news  (3 years ago)

    Introducing The Alien Warp Submitter. Five Day Blast to
    people actually interested in what you are selling. Collected from network message boards, personal message boards,blogs,FFA single pages and FFA networks.

    Purchase today and you’ll Receive a Contact-Email to 500,
    000 UNIQUE Prospects, the ION Marketing System and Premium Classified Access.
    Today you can purchase this package for just *$12.95
    be aware this offer will end anytime.

  39. all guitar things
    #46 written by all guitar things (3 years ago)

    Another highlight of this career is the possibility to climb the corporate
    ladder to become an executive music producer. You are just about never making the improper choice when you make a decision to purchase a Gibson guitar.
    This person will be able to tell you exactly what needs to
    be done in order to achieve your musical goals, and how to do it.

  40. https://www.facebook.com/Bayperfect
    #47 written by https://www.facebook.com/Bayperfect (3 years ago)

    You will have to work with your doctor to pput together an
    elimination diet, andd keeping a food journal to chart your symmptoms
    and food reactions. Kira whichh showed my body didn’t like
    cashews, coffee (Darn. You can also use your hands or a mixer with a dough
    hook to get the job done.

  41. กระเป๋าโรงเกลือ ราคาถูก

    The heat draws the pus up to the surface of the skin while the chamomile tea helps to
    reduuce swelling. If the skin around the head of a boil turns red – If you
    suffer from diabetes, heart ailments including a murmur,
    suppressed immune sgstem from medications or disease – Treaat a Boil wwith Heatt
    – Wet a small, clean towel with the hottest water you
    can stand without burning yourself. They also have a collection of bags for ladies to
    purchase as well that come with insulated cooler pockets.

  42. watch salem season watch glee season watch true blood season

    Hello would you mind letting me know which web host you’re utilizing?
    I’ve loaded your blog in 3 completely different browsers
    and I must say this blog loads a lot quicker then most.
    Can you suggest a good web hosting provider at a
    reasonable price? Thank you, I appreciate it!

  43. football match
    #50 written by football match (3 years ago)

    If some one needs to be updated with most up-to-date technologies after that he
    must be go to see this site and be up to date daily.

  44. Coquitlam personal trainer
    #51 written by Coquitlam personal trainer  (3 years ago)

    I constantly spent my half an hour to read this blog’s articles or reviews everyday along with a cup of coffee.

  45. www.arabicmusicvideosonline.com
    #52 written by www.arabicmusicvideosonline.com (3 years ago)

    Nevertheless another issue you’ll need to take careof is the baby shower wording for your baby shower invitations.

    A common household screen can be used for that purpose.
    Baby sprinkles are less demanding in terms of gifts and etiquette.

    my page; planning a baby shower at work (http://www.arabicmusicvideosonline.com)

  46. Media Bucket
    #53 written by Media Bucket  (3 years ago)

    The World Wide Web is an important marketing medium and to
    gain success in this arena a marketer should have well planned online marketing strategy.
    From customer satisfaction to the importance of certain aspects of your company,
    this is a very versatile option to use in your online marketing questionnaires.

    SEO is the most prominent tool to drive a huge traffic rate, as search engines
    really give closest attention to well-optimized pages.

    Here is my homepage Media Bucket

  47. Ashford University
    #54 written by Ashford University  (3 years ago)

    Online students have the flexibility of dictating their own individual schedules, still receiving government aid,
    and possibly getting a better education than the usual traditional student.
    As with all courses, the demands of a hybrid history
    college course can vary from school to school and professor to professor.
    ITSM will offer educational media environments that are fully interactive where trainees can take part
    in self-testing in competency-based management scenarios and applied activities.

  48. arbetaren.se
    #55 written by arbetaren.se (3 years ago)

    Interesting blog! Is your theme custom made or did
    you download it from somewhere? A design like yours with a few
    simple tweeks would really make my blog stand out.
    Please let me know where you got your design. With thanks

  49. descargar ebooks
    #56 written by descargar ebooks  (3 years ago)

    Yes! Finally something about descargar ebooks gratis.

  50. http://cheap-hotel-travel.com
    #57 written by http://cheap-hotel-travel.com  (3 years ago)

    You can even visit the Audubon Zoo to meet hundreds of different wildlife while learning how to preserve our Louisiana habitats.
    There are budget hotels near Delhi Airport for those who wish to make their stay
    near airport. Serta was the first to mattress maker
    to use convoluted foam in its upholstery.

  51. You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  52. Comment Feed for this Post
Go to Top