Drupal 7 – Add page and section body classes

October 6, 2011

Add this snippet to the template.php file in the THEMENAME_preprocess_html() hook.

<?php
global $base_path;
list(,
$path) = explode($base_path, $_SERVER['REQUEST_URI'], 2);
list(
$path,) = explode('?', $path, 2);
$path = rtrim($path, '/');
// Construct the id name from the path, replacing slashes with dashes.
$body_id = str_replace('/', '-', $path);
// Construct the class name from the first part of the path only.
list($body_class,) = explode('/', $path, 2);
// $body_class = $body_class . ' not-front';
$body_id = 'page-'. $body_id;
$body_class = 'section-'. $body_class;
$vars['classes_array'][] = ' ' . $body_id . ' ' . $body_class;
?>
Leave a comment Tags: Drupal 7

Drupal 7 – Add width and height attributes to image styles (imagecache)

August 25, 2011

Image styles (imagecache) are now included in Drupal 7 core, however the width and height attributes are not added to the <img> elements (lame). Add the below code to your template.php file to add width and height attributes to images that use image styles.

<?php
function THEMENAME_image_style($variables) {
 
$style_name = $variables['style_name'];
 
$path = $variables['path'];

 
// theme_image() can only honor the $getsize parameter with local file paths.
  // The derivative image is not created until it has been requested so the file
  // may not yet exist, in this case we just fallback to the URL.
 
$style_path = image_style_path($style_name, $path);
  if (!
file_exists($style_path)) {
   
$style_path = image_style_url($style_name, $path);
  }
 
$variables['path'] = $style_path;

  if (
is_file($style_path)) {
    if (list(
$width, $height, $type, $attributes) = @getimagesize($style_path)) {
     
$variables['width'] = $width;
     
$variables['height'] = $height;
    }
  }
 
  return
theme('image', $variables);
}
?>
1 comment Tags: Drupal

Drupal 6 – Theme search results page using nids

August 4, 2011

This theme override will supply the nids of each search result. You are free to use the nids as you please! A very useful trick is to feed the nids (as arguments) to a view, then display the view results as your search results. Endless possibilities!

Note: this function goes in the template.php file in a custom theme

<?php
/**
* Theme the search results
*/
function THEMENAME_preprocess_search_results(&$vars){
   
$nids = array();
   
// cycle through each result
   
foreach($vars['results'] as $result){   
       
// get each nid   
       
$nids[] = $result['node']->nid;
    }
   
   
/**
     * You can now use the $nids array however you please!
     * I often feed the nids to a view for an
     * uber custom search results page as shown below
     */

    // add commas between each node
   
$nids = implode(',', $nids);

   
$output = views_embed_view('VIEWNAME', $nids);

   
// this variable will display the output on the search results page
   
$vars['search_results'] = $output;   
}
?>
Leave a comment Tags: Drupal

Drupal 6 – Ubercart – fix attribute option sort for product classes

July 27, 2011

I have noticed that modifying attribute option weights (sorting with the drag n drop table) is not reflected when attribute is displayed with product classes. This is because there is a separate table named uc_class_attribute_options that Ubercart does not update when changing the order.

Adding the below code using a custom module fixes this behavior

<?php
/**
* Implementation of hook_form_alter().
*/
function MODULENAME_form_alter(&$form, $form_state, $form_id){
    if(
$form_id == 'uc_attribute_options_form'){
       
$form['#submit'][] = 'MODULENAME_attribute_options_form_submit';
    }
}

/**
* Ubercart options do not update the ordering of the uc_class_attribute_options table - product classes will not
* see the proper ordering. This additional submit handler fixes that.
*/
function MODULENAME_attribute_options_form_submit($form, &$form_state){
    foreach (
$form_state['values']['options'] as $oid => $option) {
   
db_query("UPDATE {uc_class_attribute_options} SET ordering = %d WHERE oid = %d", $option['ordering'], $oid);
  }
}
?>
1 comment Tags: Drupal, Ubercart

Drupal 6 – Ubercart – Redirect the “Cancel” button on checkout

July 22, 2011

This method will override the core redirect to '/cart' when user clicks the "Cancel" button on checkout.

First you must change the #name attribute to a custom value. Then you must check for the $_POST value of that name. If it matches, implement a custom drupal_goto call.

<?php
/**
* Implementation of hook_form_alter().
*/
function MODULENAME_form_alter(&$form, $form_state, $form_id){
   
// target the checkout form
   
if($form_id == 'uc_cart_checkout_form'){
       
// change the cancel button's #name to a custom value
       
$form['cancel']['#name'] = 'bx_cancel';
       
// check the $_POST value of your custom #name
       
if($_POST['bx_cancel'] == t('Cancel')){
           
// copied from Ubercart core
           
if (intval($_SESSION['cart_order']) > 0) {
               
uc_order_comment_save($_SESSION['cart_order'], 0, t('Customer cancelled this order from the checkout form.'));
              unset(
$_SESSION['cart_order']);
            }
           
// implement your custom redirect here
           
drupal_goto('<front>');
        }
    }   
}
?>
Leave a comment Tags: Drupal, Ubercart

Drupal 6 – Change a taxonomy listbox to a selectbox

July 21, 2011

This will change a scrolling listbox into a single selection drop-down selectbox. (Place in MODULENAME.module)

PS - change 1 to your vocabulary ID

<?php
$form
['taxonomy'][1]['#size'] = '';
$form['taxonomy'][1]['#multiple'] = 0;
?>
Leave a comment Tags: Drupal

Drupal 6 – Generate additional path alias when updating or adding a taxonomy term

July 5, 2011

This function generates an additional path alias when a new taxonomy term is created. It will also update the alias if the term is updated and delete the alias if the term is deleted.

In this example I am adding the alias 'taxonomy/term/%tid/articles' for every taxonomy term.

<?php
/**
* Implementation of hook_taxonomy().
*/
function MODULENAME_taxonomy($op, $type, $array = NULL){
    if((
$op == 'update' || $op == 'insert') && $type == 'term'){
       
       
// create an additional path alias of %path/articles
        // if alias does not exist, create new alias
       
if(db_result(db_query("SELECT COUNT(pid) FROM {url_alias} WHERE src = '%s'", 'taxonomy/term/' . $array['tid'] . '/articles')) == 0){
           
db_query("INSERT INTO {url_alias} (src, dst) VALUES ('%s', '%s')", 'taxonomy/term/' . $array['tid'] . '/articles', drupal_get_path_alias('taxonomy/term/' . $array['tid']) . '/articles');
       
// if alias exists, update the alias
       
}else{
           
db_query("UPDATE {url_alias} SET dst = '%s' WHERE src = '%s'", drupal_get_path_alias('taxonomy/term/' . $array['tid']) . '/articles', 'taxonomy/term/' . $array['tid'] . '/articles');
        }
       
    }else if(
$op == 'delete' && $type == 'term'){
       
// delete the alias
       
db_query("DELETE FROM {url_alias} WHERE src = '%s'", 'taxonomy/term/' . $array['tid'] . '/articles');
    }
}
?>
Leave a comment Tags: Drupal

Drupal 6 – Get latest Twitter feeds

June 23, 2011

This function accepts a Twitter account name, $user_id, and returns a list of the latest tweets.

Note: thanks to Chris Coyier!

<?php
/**
* Returns the latest Twitter statuses
*/
function MODULENAME_load_twitter($user_id){
   
// twitter url
   
$url = "twitter.com/statuses/user_timeline/$user_id.xml?count=10";
   
// convert to simple xml object
   
$xml = simplexml_load_file($url) or die("could not connect");
   
// start the markup
   
$output = '<ul>';
   
// cycle through each status
   
foreach($xml->status as $status){
       
// convert iso date to unix timestamp
       
$date = strtotime($status->created_at);
       
// format date
       
$date = date('n/j/Y', $date);
       
// get the status
       
$message = $status->text;
       
// convert any URL to a link
       
$regex = '/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;\'">\:\s\<\>\)\]\!])/';
       
$message = preg_replace_callback($regex, 'MODULENAME_twitter_match', $message);
       
       
// create markup
       
$output .= '<li><div>' . $date . '</div>';
       
$output .= '<div>' . $message . '</div></li>';
    }
   
// complete markup
   
$output .= '</ul>';
    return
$output;
}

/**
* Regex callback that replaces any URL with a link
*/
function MODULENAME_twitter_match($url){
    return
'<a class="' . $url[0] . '" target="_blank">' . $url[0] .'</a>';
}
?>
Leave a comment Tags: Drupal

Drupal 6 – Get Facebook status for any public profile

June 23, 2011

Seems like every time I find a method that works Facebook goes and changes the API. However, this method seems pretty solid.

First, you must enable the developer app on your Facebook account and create an app with the URL of the site on which you will be using this code. From this app you will need:

  • App ID
  • App Secret

Second, download the Facebook PHP SDK: https://github.com/facebook/php-sdk/ and include facebook.php in your module.

This function accepts one argument, ($fbid is the user's Facebook ID) and returns an object containing the specified number of statuses along with other meta data. Simply dpm() the returned object to view details.

<?php
/**
* Returns the latest Facebook statuses
*/
function MODULENAME_load_fb($fbid){
   
// include the Facebook SDK
   
require(drupal_get_path('module', 'MODULENAME') . '/facebook.php');
   
// create a new Facebook object with custom app info
   
$facebook = new Facebook(array('appId' => 'YOUR_APP_ID', 'secret' => 'YOUR_SECRET_APP_ID'));
   
// get the user status
   
$status = $facebook->api('/' . $fbid . '/feed?limit=10');

    return
$status['data'];
}
?>
3 c