How to group search results by content type in Drupal 6

03 Feb 2010
Posted by Eddie

The following code shows how I went about limiting core drupal search results to two content types, and then grouping content from those types together. In this case I stacked the content types so all of content type a would show first, followed by all content from content type b and so on. You could display the results side by side or whatever. This was done at the theme level in search-results.tpl.php


<?php 
$i=count($results);
if ($i > 0) { ?>
<h1>Search Results</h1>
<h3>You searched for <span id="query"></span></h3>
<?php } ?>

<?php print $keys; 


 for($x=0;$x<=$i;$x++){ 
	if ($results[$x]['node']->type == 'product') { ?>
	    <div class="search-box">
	        <div class="search-image">
				<img src="/<?php print $results[$x]['node']->field_productimage[0]['filepath']?>"/>
	        </div>
	        <div class="search-text">
				<div class="product-headline">
					<div class="product-headline-title">
						<a href="/node/<?php print $results[$x]['node']->nid;?>"><?php print $results[$x]['node']->field_productname[0]['safe'];?></a>
					</div>
					<div class="product-code">
						<?php print $results[$x]['node']->field_productcode[0]['value'];?>
					</div>
				</div>
				<div class="product-body">
					<?php if ($results[$x]['node']->content['body']['#value'] != NULL) { 
						print $results[$x]['node']->content['body']['#value'];
						} else {
						print 'Product information coming soon';
						} ?>
						<div class="product-details"><a href="/node/<?php print $results[$x]['node']->nid;?>">View Product Details</a></div>
				</div>
				
			</div>
		</div>
	<?php 	}
} ?>
<?php
 for($x=0;$x<=$i;$x++){ 
	if ($results[$x]['node']->type == 'animal') { ?>
	<div class="search-box animal">
		<div class="search-image">
			<img src="/<?php print $results[$x]['node']->field_thumbnail_photo[0]['filepath']?>"/>
		</div>
		<div class="search-text">
				<div class="product-headline">
					<div class="product-headline-title">
						<a href="/animals/<?php print $results[$x]['node']->title;?>"><?php print $results[$x]['node']->title;?> Care Info and FAQs</a>
					</div>

				</div>
				<div class="product-body">
					Find out more about this animal and the care needed
					<div class="product-details"><a href="/animals/<?php print $results[$x]['node']->title;?>">View <?php print $results[$x]['node']->title;?> Information</a></div>
				</div>
		</div>
	</div>
<?php	
	}
}


?>




</dl>
<?php print $pager; ?>

<script type="text/javascript">
$(document).ready(function() {
    var query = $('#edit-keys-wrapper input.form-text').val();
	$('#query').replaceWith('<span id="query">' + query + '</span>');
});

</script>

The jQuery at the end basically is just a quick way of showing the user what they searched for without having to split atoms in template.php