When working with Drupal CCK types, you may want to generate your own custom lists. Sometimes getting at the particular tags within the lists may be a chore. Here's one way to get at the information without using the DOM or hooks.
Lets say that in your blog node, you have a title and a nice picture that is meant to be floated to the left of the text.
Pictorially, it may look like this:
As you can see above, this is a list of blog nodes that contains a title, a picture, and text to the right of it.
The code for this blog node may look something like below:
<h2>Your Title Here</h2> <img style="float:left; margin: 1em 1em 1em 0" src="image.jpg" alt="Image"/> <p>A paragraph of teaser text</p> <p>A paragraph of non-teaser text</p>
Now suppose you want a PHP snippet that shows the five recent blog nodes above, in a list, but without the text. That is, you want a new list with only the title and the image within it. Something like this:
How do you pull this off?
Let's start with this PHP snippet which generates a list of teasers:
<?php function GetLatestTeasersAsList($className, $contentType, $startEntry, $num, $excludeUserIds="0") { $outContentType = ""; $types = explode(",", $contentType); $numTypes = count($types); $typeCount = 1; foreach($types as $type) { $outContentType .= "n.type = '{$type}'"; if ($typeCount++ < $numTypes) $outContentType .= " OR "; } $result1 = db_query_range(db_rewrite_sql("SELECT n.nid, n.created FROM {node} n WHERE {$outContentType} AND n.status = 1 AND n.uid NOT IN ({$excludeUserIds}) AND n.sticky = 0 ORDER BY n.created DESC"), $startEntry, $num); $output2 = "<ul class='{$className}'>"; while ($node = db_fetch_object($result1)) { $output2 .= "<li>" . node_view(node_load(array('nid' => $node->nid)), 1) . "</li>"; } $output2 .= "</ul>"; return $output2; } ?>
Variables:
classname is the name of the list class
contentType is your CCK type. In this case we are using "blog"
startEntry is the position (0 beginning)
num is the number of teaser nodes you want in the list
excludeUserId is a list of CSV user Ids. The blog nodes are excluded for these users.
Usage:
The code below will generate an unordered list with classname "latest-blog" and generate the last five blog nodes.
If you look at the source code generated, you will see markup in there you don't need. Our goal at the start of this article was to get just the image and title.
So how do we just get just that markup? One way is to use regular expressions. We can pull out all the image tags and the h2 title tags with two calls:
This would give us two arrays with the image and title text for each blog. Notice in the regular expression for the h2 header tag, I pull out everything between the h2's. This is because if you have anchor tags between it, you will want to retain them.
Next, we can now regenerate the list with some extra bit of markup: