I have a magazine like post structure like so: Parent -> Sub category -> Article.

The parent is the issue, the sub categories are the sections within the magazine like news and interviews etc and then the articles are within those sections.

I have background images which are associated with the sub category and then articles within that sub category inherit the background image. Code in single.php which retrieves the background image from its sub category hence [1] not its top level parent [0].

$category = get_the_category();
$hierarchy = array_reverse( get_ancestors( $category[0]->term_id, 'category' ) );
$hierarchy[] = $category[0]->term_id; 

<body style="background:url('<?php echo z_taxonomy_image_url($hierarchy[1]); ?>')" class="background-img">

For the most part this works just fine, however on a few articles the background image doesn't show. I have breadcrumbs showing the category structure and the posts that work show the full parent -> sub category -> post name structure, however on the ones that don't work just shows parent -> post name. There is the standard wordpress breadcrumbs and meta info at the bottom which always displays the correct heirachy for the post which is why I am confused.

How come some posts how their correct heirachy whilst others don't?

My permalink structure is index.php/category/postname

You can check the bug out here post with background and proper taxonomy at the top

post with incorrect hierarchy here so no background and incorrect breadcrumbs at the top

  • 1
    In the backend, is the sub category checked, or is the subcategory AND its parent checked?
    – Tom J Nowell
    Dec 5, 2012 at 16:24
  • Yep both categories are checked correctly on every single one. Should it only be the sub category that is checked? Dec 5, 2012 at 17:22
  • stick it as an answer mate and ill gladly tick it. having the post in its parent category and sub category cinfused things, should only be in the sub category. Dec 5, 2012 at 17:27

1 Answer 1


Your code is failing because the first term is the parent term, caused by checking both the parent and the child term.

You dont need to do that, if I have a heirarchy A->B->C->post, and I add the post to the C category, it's automatically a part of its parents

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.