0

I'm using:

$category = get_the_category();
echo $category[0]->cat_name;

to display the current category as a header in an archive template (example of local url is http://imac.local:5757/category/accommodation/, http://imac.local:5757/category/service/ etc)

For the first 3 categories, this works fine, but after that it's showing a child category instead. I've tried changing the slug of the posts and the category, updating the permalinks, unpublishing posts in the child category which is showing (it then shows another child category instead) - but none of this solves the problem.

I suppose it's a clash of slugs & permalinks somewhere, but changing these doesn't seem to fix it. Is there more specific wordpress php which can be written to avoid this clashing?

I did find this post: Archived Posts in Wrong Category but it doesn't seem to be the same problem.

Thanks

1

As far a I can understand you need to display the category name for the current page when viewing a category page.

You can make use of the query variables to retrieve the category name, for example:

$category = get_queried_object('cat'); 
echo $category->name;

EDIT

A global check to see what is returned by the main query for a specific page/template, you can do a var_dump of the main query global, $wp_query. Add the following code inside your template outside of the loop

?><pre><?php var_dump($wp_query); ?></pre><?php 

To check which query variables are available on a template/page, you can do a var_dump of get_queried_object()

$queried_object = get_queried_object();
 var_dump( $queried_object );

Here is also a list of all query variables

| improve this answer | |
  • Thanks Pieter - but this doesn't actually show anything at all... – Dave Oct 10 '14 at 11:32
  • How does your file structure look like. Are you using custom taxonomies and or custom post types. Do var_dump($wp_query) anywhere outside the loop in your template – Pieter Goosen Oct 10 '14 at 12:47
  • Ah yeh - it's a custom post type. Would that make a difference when echoing out the category titles? var_dump($wp_query) for cat echos out ["cat"]=> int(6) - which is actually the ID for the correct category that should be displaying. I think we're onto something here :P – Dave Oct 10 '14 at 13:28
  • 1
    Please see my updated code – Pieter Goosen Oct 11 '14 at 6:26
  • Hooray! That's perfect - thanks so much. So, I suppose this same method will work for any data outputted in var_dump($wp_query)? Replacing cat with whatever I need to echo out...? – Dave Oct 12 '14 at 16:06

Your Answer

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

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