background image
HomeRecent PostsDrupalSearchTagsRSSContactAboutAccount
Eric.London's picture

I recently signed up for Google AdSense and I thought it would be fun to show ads for Internet Explorer users. Of course, you could use this tutorial for more productive purposes. Here is how I integrated this functionality into my theme.

I added 2 regions to THEME.info file:

regions[ad_left] = Ad Left
regions[ad_right] = Ad Right

I then included the regions in my theme by adding some code to my theme's page.tpl.php file:

<?php if ($ad_left): ?>
  <div id='ad_left' class='google_ads'>
    <?php print $ad_left; ?>
  </div>
<?php endif; ?>

<?php if ($ad_right): ?>
  <div id='ad_right' class='google_ads'>
    <?php print $ad_right; ?>
  </div>
<?php endif; ?>

Next, I added some CSS in my style.css theme file to absolutely position the regions in a fixed position:

.google_ads {
  position: absolute;
  bottom: 10px;
  width: 120px;
  height: 600px;
  display: none;
}

.google_ads .block {
  padding: 0;
  margin: 0;
}

body > .google_ads {
  position: fixed;
}

#ad_left {
  left: 10px; 
}

#ad_right {
  right: 10px;
}

Now that my regions were setup, I added 2 blocks containing the Google AdSense code and assigned the blocks to my new regions. You'll need to make sure the input filter you choose allows for javascript to be included.

At this point, the ads are included for every browser, but they will not be shown due to the "display: none" property I added to the "google_ads" CSS class. I added a few lines of jQuery in my theme's script.js file to show the regions for IE users:

$(document).ready(function(){
  // per IE ads
  if ($.browser.msie) {
    $('.google_ads').show();  
  }
});

If you view this page in IE, you'll see my code in action ^_^

My additional thoughts... this code executes the Google AdSense javascript regardless of your browser, but it is only shown to IE users. A more efficient method would be to use AJAX to include the javascript ONLY if the browser is IE, or of course, by implementing a server side browser detection library.

When using views to handle the taxonomy term pages, you may not have the taxonomy term description available in your page variable scope (either page.tpl.php or page-taxonomy.tpl.php). If you'd like to display it at the top of the page, you can add a preprocess function in your theme to add the variable:

<?php
function MYTHEME_preprocess_page(&$variables) {
 
// check to see if this is a taxonomy term page
 
if (arg(0)=='taxonomy' && arg(1)=='term') {
   
// load the taxonomy term object
   
$term = taxonomy_get_term(arg(2));

   
// add the taxonomy term description to the variables
   
$variables['taxonomy_term_description'] = $term->description;
  }   
}
?>

Now in your page.tpl.php (or page-taxonomy.tpl.php) file, you can add the following line of PHP to output the description. NOTE: I enclosed it in a div with a class so I can add necessary CSS easily.

<?php
if ($taxonomy_term_description) print "<div class='taxonomy_term_description'>$taxonomy_term_description</div>";
?>

Adding this code to your Drupal site can improve two sections of a YSlow report, "Make fewer HTTP requests" and "Minify JS". This function minifies and aggregates your javascript into a single file. It requires the Google code library jsmin-php (http://code.google.com/p/jsmin-php/).

Stick this function in your template.php file in your theme directory:

<?php
function minify_scripts($scripts) {

 
// define paths
 
$jsMinFileName = 'jsmin_minified.js';
 
$jsMinAbsolutePathDir = getcwd() . '/' . file_directory_path();
 
$jsMinAbsolutePath = $jsMinAbsolutePathDir . '/' . $jsMinFileName;
 
$jsMinRelativePath = base_path() . file_create_path($jsMinFileName);   
   
 
// check to see if file is writable
 
if (
    (!
file_exists($jsMinAbsolutePath) && !is_writable($jsMinAbsolutePathDir))
    ||
    (
file_exists($jsMinAbsolutePath) && !is_writable($jsMinAbsolutePath))
    ) {
    return
$scripts;   
  }
   
 
// include js minify library
 
require_once('jsmin-1.1.1.php');

 
// split $scripts on new line
 
$exploded = explode("\n", trim($scripts));

 
$minifiedJS = "";
  foreach (
$exploded as $k => $v) {

   
// ensure this line is javascript
   
if (!(substr($v,0,7)=='<script' && substr($v,-9)=='</script>')) continue;
       
   
// convert <script> to xml
   
$xml = simplexml_load_string($v);
       
    if (
$xml['type']=='text/javascript' && strlen($xml['src'])) {

     
// define path to old file
     
$oldFile = getcwd() . $xml['src'];
           
     
// minify javascript
     
$minifiedJS .= JSMin::minify(file_get_contents($oldFile));

     
// unset exploded array entry
     
unset($exploded[$k]);
           
    }
       
  }
   
 
// check to see if javascript has not been minified
 
if (strlen($minifiedJS)==0) return $scripts;

 
// write file
 
file_put_contents($jsMinAbsolutePath, $minifiedJS);
   
 
// re-index array
 
sort($exploded);

 
// add entry
 
$exploded[] = "<script type='text/javascript' src='$jsMinRelativePath'></script>";
   
  return
implode("\n", $exploded);
   
}
?>

In your page.tpl.php theme file, replace this line...

<?php
print $scripts
?>

with
<?php
print minify_scripts($scripts);
?>

You can also improve your score in the "Put JS at the bottom" section by ensuring this line of code resides at the bottom of your page.tpl.php file. I insert it just before this line:

<?php
print $closure;
?>

When creating a theme, it's important to keep your layout flexible in order to avoid wasted space. Here's a quick tutorial to show you how to vary theme layouts based on the contents of a region. Consider a common layout that contains 3 columns: sidebar_left, content, and sidebar_right. If the sidebar_right region did not have any blocks assigned to it, you could conserve valuable space by revising your theme layout using CSS and theme variables.

The first thing to do is add a variable to the page.php.tpl scope of your theme. In your template.php file, add a function called _phptemplate_variables. The following code checks the currently assigned variables to see if html has been assigned to the regions. If the region is empty, a variable will be passed to the theme containing CSS class selectors.

<?php
function _phptemplate_variables($hook, $vars=array()) {
  switch(
$hook) {
    case
'page':
     
$layoutClasses = array();
      if (!
$vars['sidebar_right']) $layoutClasses[] = 'noSidebarRight';
      if (!
$vars['sidebar_left']) $layoutClasses[] = 'noSidebarLeft';
     
$vars['layoutClasses'] = implode(' ', $layoutClasses);
      break;
  }
  return
$vars;
}
?>

Next, in your page.tpl.php, locate the div in your layout that your like to conditionally change. Add the following code to add the CSS class selectors as necessary.

<?php
<div id='layoutContent' class='<?php print $layoutClasses; ? >' >
 
BLAH BLAH BLAH
</div>
?>

Last, you can add CSS to revise your layout. In this case, I'll change the width of my divs.

#layoutContent {
  width: 500px;
}

#layoutContent.noSidebarRight {
  width: 750px;
}

#layoutContent.noSidebarLeft {
  width: 750px;
}

#layoutContent.noSidebarLeft.noSidebarRight {
  width: 1000px;
}

In this example I'll show how you can display certain pages with an alternate theme layout. In a real world example, I added some jQuery to my module to allow the user to open a new window and allow them to add a node. The newly opened window had to bypass my regular theming to function properly.

I wanted my custom theme layout to start right after my closing </head> tag and before my opening <body> tag, so I inserted this line of PHP code in my page.tpl.php file:

<?php
theme
('check_no_theme', $variables);
?>

Next, I added a function to my theme template.php file. This function checks to see if the query string matches an entry in a defined array and then uses the _phptemplate_callback function to load a theme file called "notheme-page.tpl.php".

<?php
function MYTHEME_check_no_theme(&$variables) {

 
// create a list of q values that will have no theming
 
$noThemeQs = array('MYPAGE_1', 'MYPAGE_2', 'MYPAGE_3');
   
  if (
in_array($_REQUEST['q'], $noThemeQs)) {
   
_phptemplate_callback('notheme-page', $variables);
  }
}
?>

Last, I create a file called notheme.page.tpl.php. This file contains the alternate page.tpl.php html. NOTE: the PHP "die" statement is important from keeping the original theme from being displayed.

  <body>
    INSERT YOUR ALTERNATE THEME LAYOUT HERE
  </body>
  <?php print $closure; ?>
</html>
<?php die; ?>

Syndicate content