Wordpress: Change page header based on the category or sub category

So I am going to start adding a little bit of php to this site.  Whatever helps people.

This is pretty basic but caused me  a bit of trouble.  I needed to have the page header on a wordpress blog change if the user was in the 'Blog' category.

I thought it would be pretty easy but then I thought 2 things:

1.  What if the category is a sub category of the blog category and

2.  What if the user was viewing a post in the blog category or a blog sub category.

Do you need to write a ton of if statements to get this done?  When the client adds a category do you need to edit the code to account for this.  No.

So here is how we do it (in the header.php file):

Get the array of categories based on the post id.

PHP:
  1. $categories = get_the_category($post->ID);

Here we are using a wordpress function called get_the_category().  This returns an array of all the categories associated with the page including the current and parent categories.
$post->ID gets the current id out of the $post array.  This could be a post ID or a category ID.  It doesn't matter.  After this runs $categories will contain a bunch of information about all the categories related to this page or post.

Next I set up an empty variable to hold my category id(s).

PHP:
  1. $catArray = array();

Next I loop though the $categories variable to get the category id's out and put them in the $catArray variable.  Since the $categories array holds a bunch of stuff we don't need we use this to get what we want: the IDs.  The reason I am going to put them in an array is because it will be nice neat and organized.

PHP:
  1. for($i = 0; $i < sizeof($categories); $i++){
  2. array_push($catArray, $categories[$i]->cat_ID);
  3. }

This is a basic php loop.  It says start at 0 and count though the $categories loop until there are no more entries.  It will step though the array line by line kinda like searching an excel spreadsheet.
Sizeof is how the php knows how large the $categories array. So the first line of the loop says, start at $i which is equal to zero, Stop when $i = the size of the $catergories array, and count by one (do one row at a time).

The array_push line takes the id out of the $categories array and stores it in the $catArray array.  So we went from a big array with a bunch of info we dont need ($categories) to an array $catArray that just has the categories in it(like this: 33, 44, 231).

So now that we have an array with all the category id's associated with our post, now we can search it and test if it is associated with the blog id.

PHP:
  1. if(in_array(130, $catArray)){$isBlog = true;}

130 is the id of the blog category.  This line of code says that if 130 is in the $catArray then set $isBlog to true.

So now we have a variable that lets us know that yes we are in the blog category.  We can use that in the rest of the page to make decisions on what to and what not to show.

So somewhere in your script for the page you do this

HTML:
  1. <div id="header" class="<?php if($isBlog == true){echo 'blog_header';} else{echo 'standard_header';}?>">

This will assign the class blog_header if it is part of the blog and standard_header if it is something else.  Then  you just change your css accordingly and it works.

Disclaimer:  I don't claim to be a wordpress php expert, I am learning just like you!

9 comments ↓

#1 Dick Kirkland on 07.14.09 at 10:03 am

Thanks for the tips. Keep these WP topics comin’ too.
your bud,
Dick

#2 Eddie on 07.14.09 at 10:08 am

do work Dick

#3 Скачать покер бесплатно on 10.05.09 at 11:18 am

Спасибо. было познавательно.

#4 Pol36 on 10.10.09 at 3:47 pm

The volume can be centrally managed here thanks to the pulse audio system. ,

#5 Скачать виртуальное казино on 12.08.09 at 9:43 am

Прямо в точку. Здесь наиболее полно раскрыты все аспекты этого вопроса, что достаточно большая редкость.

#6 aze on 12.31.09 at 1:43 am

Thanks for sharing :
Really nice tip, exactly what i was searching

#7 Мастер Авто on 03.07.10 at 4:00 pm

Очень понравилось написанное. Надеюсь, пригодится в скором будущем. Стоит продолжить.

#8 Скачать фотошоп on 03.08.10 at 8:12 am

хорошая новость: “Мисс Россия-2010″ И.Антоненко получила сертификат на 100 тыс. долларов, корону, украшенную россыпью из 2,5 тысяч бриллиантов и редких жемчужин, а также право представлять Россию на конкурсе “Мисс Мира”.

скачать фотошоп

#9 LikeGermany on 04.14.10 at 11:00 am

Не пойму в чём дело, но у меня тока 2 картинки загрузилось. ((( А ваще понравились!

Leave a Comment

Buy clomid online
Buy zovirax online
Buy cipro online
Buy nexium online
Buy diflucan online
Buy lasix online
Buy neurontin online
Buy synthroid online
Buy flagyl online
Buy nolvadex online