How To Get A Node Object By The Page Title In Drupal

Sometimes you may have the desire, or requirement, to get a node object and all you know is the page title. Currently, Drupal does not have a function (that I know of ) for getting access to a node object this way. And why would they --the Drupal architecture allows you to have two or more posts with the same title. Still, the way you manage a site may not ever have two posts of the same name, and you're trying to automate something where getting that node by the title is just what you need.


With this little function below, you can easily get a node object by passing the title alone. Here's the function:

function theme_get_page_by_title( $page_title ) {

    if ( $query = db_query( "SELECT * FROM {node} WHERE    {node.title}='%s' limit %s", $page_title, 1 ) ){

        $node = db_fetch_object( $query );        return $node;    }    else {

        return false;    }} 

What we're doing is very basic; you pass in the title and it matches a title to the node in the database and ensures we limit it to one match. It will grab the first entry it finds in the event you have multiples. We then fetch the object, and there's your node object.

You can add this function to your themes template.php file. Make sure to change theme in theme_get_page_by_title with your theme name, e.g. mytheme_get_page_by_title. Refresh your cache by going to Administrator->performance and then you can call it like so:

$_node = mytheme_get_page_by_title( 'My First Post' );

However, you may want to load that node to get all the node information. Simply use node_load() with the node id:

$node_page = node_load( $_node->nid );

Now, you can access your node object properties and contents.