WordPress: different header images for different categories

If your theme has a header image, this article is for you.   It turns out, it is relatively easy to display different site header images for different post categories.

To do that, you need to add an IF statement to header.php file.  This IF statement will control, what header image is loaded depending on (in this example) current category.

First, upload a new header image using new article and add new media functionality. Note the path, where your new header image landed in the Upload directory structure.

Here is how header image code looked before the change in header.php:

 

<?php if(pbt_theme_option('logo_header')) { ?>
         <a href="<?php echo home_url(); ?>/" class="headerimage">
               <img src="<?php echo pbt_theme_option('logo_header'); ?>
               " alt="<?php bloginfo('name'); ?>"<?php echo $float; ?> /></a>
<?php } else { ?>

 

Here is a modified code that checks for the category ID 555, and outputs a different header image, if this category is detected:

<?php if(pbt_theme_option('logo_header')) { ?>
<a href="<?php 
        if(get_query_var('cat')== 555 || (get_the_category()[0]->term_id  == '555' 
 && get_query_var('p')!= 0 ))
        {
 echo ("/?cat=555"); ?>"><img src="<?php 
 echo ("/wp-content/uploads/20YY/MM/NewLogo.jpg"); ?>" <?php 
        }
        else
        {
 echo home_url(); ?>/">
 <img src="<?php echo pbt_theme_option('logo_header'); ?>" <?php 
        } ?>
alt="<?php bloginfo('name'); ?>"<?php echo $float; ?> /></a>
<?php } else { ?>

 

New logo for category ID 555 will be displayed:
        =01= if ‘cat’ is detected in query string (/?cat=555), or
        =02= if category ID of the current post (/?p=NNNN) is 555.

The IF statement looks more complicated, because you also have to eliminate situations, when there is no page ID is specified.

One more complication comes from the fact that you need to change not only the image, but also a HREF link for that image.  Before your had simply:


<a href="<?php echo home_url(); ?>/"
With a new modification you now have:

<a href="<?php if(  get_query_var('cat')== 555 || 
                   (get_the_category()[0]->term_id  == '555'  && get_query_var('p')!= 0 )) . . .  

When new logo displayed, the click on this new logo should bring the user to category home page – echo (“/?cat=555”), not to a site default home page – echo home_url().

To see how header image changes on this site, click on SportWebCenter menu, and note that header image changes to a different one.

[last revised 2015-11-05 TH 15:55]
(Visited 115 times, 1 visits today)

2 Comments

  1. Hey, I cant view your site properly within Google Chrome, I actually hope you look into fixing this.

  2. Hello, I enjoy reading all of your article post. I wanted to write a little comment to support you.

Your question, correction or clarification Ваш вопрос, поправка или уточнение