0

on my blog www.gamerwithadegree.com I have a few categories with unique names.

I have a small function in functions.php

function gwad_cat_name(){

    $categories = get_the_category();

if ( ! empty( $categories ) ) {
    echo esc_html( $categories[0]->category_nicename );   
}

};

This function gets the category nice name so I can then add it as a class like so

<div class='archive-header <?php gwad_cat_name() ?>'>

This is to allow me to define a different header background in css for each category.

If you visit the blog you will see that the PlayStation 4 category is showing the nicename for category Destiny 2, I am not sure why this is happening.

I have recently only made the header (logo nav, etc) sticky and added a wrapper div in the archive template .archive-wrapper just to be able to push down the content a bit to compensate for the fixed header.

My local test site works fine and the code is the same, I have no idea why this is happening.

I have purged all caches from W3 total cache, updated permalinks and checked the slugs in category admin, the slugs have not changed.

Anyone got any ideas why this is happening?

Thank you.

1

The reason why your function is not working as it should is because it is getting the category of the last post loaded in the loop i.e The current post 'PS4 Pro Glacier White Destiny 2 Bundle Announced'. I'm guessing the post is in two categories ps4 and destiny-2.

To customise the current category you can create a new template named category-slug.php (see category templates codex link below) specifically.

Alternatively, you can use get_queried_object() which will return the current queried object (or null) see codex link below for this function also.

You can use code similar to this:

function wpse_273435_check_current_category() {
    $term = get_queried_object();

    if($term !== null) {
        $term = $term->slug;

        if('your-cat-slug' === $term) {
            //do your thing
        }
    }
}

or if you're in category.php you could do it without the function and conditionally load a template part using get_template_part() and load a different template part based on the current category being queried.

https://developer.wordpress.org/reference/functions/get_template_part/ https://codex.wordpress.org/Category_Templates https://codex.wordpress.org/Function_Reference/get_queried_object

  • Hi thank you for your answer, you are correct the last post is in the ps4 and destiny 2 categories, I never even thought of that as a cause. I think I will implement the category-playstation-4 template, that seems the easiest for me to do. Thank you again for your help. – Destiny2Gamer Jul 15 '17 at 8:19

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.