Drupal has a core module called "Path" that allows you to set your own url name, instead of the node/40039 or other number Drupal will assign to new content posts and pages. Now, perhaps I overlooked something in my configuration, but I noticed when I put Drupal in charge of printing out the url path, it does not give me access to my alternate path, but the node/38858 or whatever number instead.
The path will still respond to the alternate path name I gave it, so I came up with a small function that will allow me to pass the node path and get back the alternate url path, if it exists. Here's the code:
function get_url_alias( $src ){
if ( $query = db_query( "SELECT * FROM {url_alias}
WHERE src='%s'", $src ) ){
if ( $rs = db_fetch_object( $query ) ){
return $rs->dst;
}
else {
return $src;
}
}
else {
return $src;
}
}
You can add this function to your template.php file in your theme to access it.
In the example above, you pass the node path you want to lookup the alternate path, or the url alias, for. If it can't find any url alias, it simply returns the node path. So, if you are automating a list of links, you can simply loop through your result that contains the paths, and pass the node path.
One way I do this is for manually displaying primary links somewhere, instead of using Drupal's block controller for it:
<?php $menus = menu_primary_links(); ?>
<?php foreach ( $menus as $menu ): ?>
<a href="<?php print $url .
get_url_alias( $menu['href'] ); ?>">
<?php print $menu['title']; ?></a>
<?php endforeach; ?>
In the example above, I am looping through the primary links and for each result, passing the node path that's contained in $menu['href']. In the event there is no url alias associated with the node path, the link that's printed out is the regular node path, so there's no need to check your results. A simple and elegant solution to the problem.
What this function does is access the url_alias table that appears to be generated when enabling the Path module. This table holds the references to the node paths in question. A simple lookup is all that's required, and if nothing is found, it returns whatever was passed in.
So, I guess there is SOME safety you may want add to this routine, and that's checking to see if your node path context is proper before trying to pass it to get_url_alias. The function won't bomb if you pass something else, but you may be able to save your self some head aches.
