I want to pass a URL to a function. This function should get the node ID from the URL.

How to do this?


You can try the following code (please note that about-us is merely an example page - you can put whichever page you want here):

$url = 'about-us';
$path = drupal_lookup_path('source', $url);

if ($path) {
  $node = menu_get_object('node', 1, $path);    
  return $node->nid;
else {
  //Error handling in case path provided does not exist

The code above returns a whole node object though, which might be expensive depending on how often you run it - another option would be to run explode() on the output of drupal_lookup_path() and just take the NID that way.




|improve this answer|||||

You may try the following one-liner:

$nid = end((arg())); // Get the last number from the URL.
|improve this answer|||||

You can read the URL values using arg() function.

For Example,

If your url is node/100 then

$argument_one = arg(0); // This will store "node" to the variable.
$node_id = arg(1); // This will store 100 to $node_id variable.

Like above using arg() function you read the URL components.

Hope it solves your issue !

|improve this answer|||||
  • what if i wanted to get the node ID of some other URL (refferal) – Rami Dabain Oct 1 '12 at 9:53
  • What do you mean by some other URL ? Can you post example URL ? – Anil Sagar Oct 1 '12 at 9:54
  • yes , for example : $nid = getNodeId($URL); ... i want to pass the URL to a function . i didn't mean with my question that i want to extract the node ID of the current URL – Rami Dabain Oct 1 '12 at 11:45

Theirs tonnes of different ways to "pass the url to a function" which way suits best depends on the situation and preference really.

What is the exact purpose of passing this URL with the node id? is there going to need to be multiple Node ID's passed at any one point? More details would mean a more detailed answer also.

$URL = $_GET['q']
// if using this then the full path needs prepending as this only gets node/nid
$URL = current_path(); // same as GET[q] basically 

// then this passes to that function you wanted
$nid = getNodeId($URL);
|improve this answer|||||
  • He is asking for a function which will give him node id of any path(alias) passed to the function – Gokul N K Feb 12 '14 at 6:20

You could break the url string into an array as

$url_arr = explode('/', $url);

Then you can access the url parts from the array.

|improve this answer|||||
  • $url variable is not defined by default. – saadlulu Aug 17 '13 at 9:54

Pass the variable (node id) appending it to url like this:

    $nodeid = $node->nid;

<a href="http://www.mysite.com?nodeid="<? php print ($nodeid) ?>">

and then in get the value from url like:


And then pass the value to the function.


|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.