This is because products can be attached to several categories. In your situation, when you visit the product page indicated on the category page, your session contains category information. But if you go directly to the product page, Magento cannot know which category you came from, so it cannot show you a specific category because your product can have several categories.
But in your situation, if your products are attached to only one category, you can use this code, it shows the name of the product in the first category;
$categoryIds = $_product->getCategoryIds(); if(count($categoryIds) ){ $firstCategoryId = $categoryIds[0]; $_category = Mage::getModel('catalog/category')->load($firstCategoryId); echo $_category->getName(); }
source share