This week I’ve had the need to render separate Drupal themes based on the node that a visitor landed on first, AND keep that theme for that user throughout their browsing of the website, even if they browsed to one of the other themed nodes.
So, if during the first visit to the website, the user landed at domain.com/marbles, they would have a nice blue theme throughout their browsing experience, but if they landed on domain.com/bananas, their theme would be red and remain red even if they went to /marbles. Make sense? The issue here is that there is no user registration — so we can’t simply just stick a theme to their user ID. The solution was to create a cookie with jq.cookie and set the value of that cookie to the name of the node they landed on, THEN we’ll pull that value to trigger a separate stylesheet for each color that we need to use.
So here’s how it’s done:
Your first objective is to _attempt_ to pull the cookie value on the main page of the website (domain.com) if the cookie exists (if they landed on one of the themed node pages), if it doesn’t exist we just don’t do anything and display the default theme. So, we call the cookie in our <head> AFTER the main style.css:
<script type="text/javascript"> var style = ''; function siteStyle() { if(jQuery.cookie("colorcookie") == "marbles") { var style = '/blue.css'; } else if(jQuery.cookie("colorcookie") == "bananas") { var style = '/red.css'; } else { return false; } return style; } <?php if($node->type != 'landing_pages') { print "var thisstyle =siteStyle(); if(thisstyle != '') { jQuery('head').append('
‘); }”;}?>
We’re using a php if statement here because we don’t want this code executing on the themed node pages. Why? Because it would execute prior to the cookie being set by the node and therefor wouldn’t do anything at all, as there is no cookie to get the value from. So we have to do it a little differently for the themed node pages in node-node_name.tpl.php
//this is where the magic happens -- we're setting the cookie based on the value of a hidden CCK field //which will tell us which page we landed on first if ($node->field_whichnode[0]['value'] == 'marbles') { print ''; } elseif($node->field_whichnode[0]['value'] == 'bananas') { print ''; }
Now that we have our cookies set, we’re now able to set which theme (stylesheet) we’re going to use. So we’ll just add that to the header with drupal_add_css
if ($node->field_practice[0]['value'] == 'marbles') { drupal_add_css( drupal_get_path('theme', 'danland') .'/green.css', 'theme'); } else if ($node->field_practice[0]['value'] == 'bananas') { drupal_add_css( drupal_get_path('theme', 'danland') .'/red.css', 'theme'); }
And there you have it, now all you have to do is create your stylesheets and override the values from the default stylesheet to change anything that can be styled.