How to run your own query through Views 1.x

Last modified: October 4, 2007 - 22:17

This is something you might not ALWAYS want to do, however you could find this useful in terms of using the Views theming layer... Here is a snippet showing how to create a block to output a list of nodes...

<?php
function get_relevant_nodes($terms) {
  if (empty(
$terms)) {
    return
t('There are no terms provided...');
  }
  else {
   
views_load_cache();
   
views_load_query();
   
   
$view = views_create_view('view_id_goes_here', 'View Description Goes Here');
   
   
views_view_add_block($view, 'Title Of Block', 'list', 3, 0, 0);
   
   
views_view_add_field($view, 'n', 'title', '', false, 0, 'views_handler_field_nodelink');
   
   
$args = implode(',', array_keys($terms));
   
   
$result = db_query('SELECT
                          n.nid,
                          n.title AS n_title,
                          COUNT(*) AS cnt
                        FROM {node} n
                        LEFT JOIN {term_node} tn ON tn.nid = n.nid AND tn.tid IN (%s)
                        WHERE n.type = "blog" AND tn.tid IS NOT NULL
                        GROUP BY n.nid
                        ORDER BY cnt DESC, n.created DESC
                        LIMIT 3'
, $args);
   
   
$items = array();
    while (
$item = db_fetch_object($result)) {
     
$items[] = $item;
    }
   
   
$view->build_type = 'block';
   
$view->type = 'list';
   
$view->num_rows = 3;
   
   
views_sanitize_view($view);
   
    return
views_theme('views_view', $view, 'block', $items, NULL, array());
  }
}
?>

This function expects an array of terms where they keys are the term ID's. If the array is empty, return a status message. If not, load the cache and query part of views (this invokes some include files). Next you create a basic view object. The next two commands define a block and a field for the list. Next I create comma separated terms and pass them into my SQL. This SQL creates a list of nodes of the type 'blog' which are tagged with at least 1 or the terms provided and then orders them by how many matching terms there were (and then on node created). This provides a list of nodes "most relevant" to the set of terms provided.

Next each node (ID, title and count) is put into an array. and 3 final view variables are set. I dont know if num_rows is needed...

The sanitizing goes over the view and "finishes it off" by doing things like figuring out the field name, etc. Finally, return the themed output!

 
 

Drupal is a registered trademark of Dries Buytaert.