Apparently global does the trick. The problem was that my variable $categories should have been redefined with a global in front of it, in each template I needed to use it.
global
$categories
Read Article https://develop.horje.com/learn/1434/reference