Adding Canonical Tags To a Drupal View
Published:
Heads up! This content is more than six months old. Take some time to verify everything still works as expected.
The Metatags module is great. The things it does automatically across the system is really fantastic, but there's one major problem. It can't add tags to views. That's not so bad, except that paged data might really benefit from canonical links. There are multiple modules in development right now that could be used to solve this issue, but nothing I've found that is really solid. So, here is a simple hook fix you could implement from a custom module to handle the gap for now.
I've also included kind of a shameful yet useful hack in here as well that can read the description off the view's menu item. I don't think it's a solid long term solution, but if you really want a description, it's an option for you.
/** * Implementation of hook_views_pre_render() * http://api.drupal.org/api/views/docs%21views.api.php/function/hook_views_pre_render/7 */ function custom_views_pre_render($view){ // Setup meta data for the view pages if( $view->display_handler->plugin_name == 'page' ){ // Canonical link back to their page $element = array( '#tag' => 'link', // The #tag is the html tag - <link /> '#attributes' => array( // Set up an array of attributes inside the tag 'href' => url( $view->display_handler->get_url() ), 'rel' => 'canonical', ), ); drupal_add_html_head($element, 'canonical'); // Description if( !empty($view->display_handler->options['menu']['description']) ){ $element = array( '#tag' => 'meta', '#attributes' => array( 'name' => 'description', 'content' => t($view->display_handler->options['menu']['description']), ), ); drupal_add_html_head($element, 'meta_description'); } } switch($view->name){ } }