Basic guide to using the processwire $page variable

Posted 21st Sep 2017

#api #pagevariable

The $page variable gives you access to information about the page you are currently viewing and comes with lots of useful functions.

The following code comes from my 'basic-page' template which is used to output my 'About me' page.

<?php namespace ProcessWire; ?>

<h1><?php echo $page->title; ?></h1>

<p>The page ID is: <?php echo $page->id; ?></p>
<p>This page uses the '<?php echo $page->template; ?>' template.</p>
<p>The URL of this page is '<?php echo $page->url; ?>'</p>

<p>It's parents page object is <?php echo $page->parent; ?></p>
<p>It's parents page ID is <?php echo $page->parentID; ?></p>

...which outputs at '/about-me/':

<h1>About me</h1>

<p>The page ID is: 1015</p>
<p>This page uses the 'basic-page' template.</p>
<p>The URL of this page is '/about-me/'</p>

<p>It's parents page object is 1</P>
<p>It's parents page ID is 1</P>

The parents page ID is 1 because the parent of my 'About me' page is 'Home' which has the ID of 1. But what about the parents page object? What is that?

If you open the cheatsheet here and click on 'Sections > $page' and click on '$page->parent', the description says:

"The parent Page object or a NullPage if there is no parent."

So, it seems a page object has been printed. So we can take this further and access things on the parent page now too:

<h2>The parent object</h2>
<p>It's parent pages title is '<?php echo $page->parent->title; ?>'</p>
<a href="<?php echo $page->parent->url; ?>">I am a link to the parent page!</a>

...which outputs:

<h2>The parent object</h2>
<p>It's parent pages title is 'Home'</p>
<a href="/">I am a link to the parent page!</a>

You'll see on the cheatsheet that it's pretty simple to get all sorts of information about the current page. Another cool use for this is changing the page title based in the template, and being able to get fields based on whether they exist of not:

<?php
  // if we are on a page created with category-entry
  // template (e.g. '/categories/api/')
  if ($page->template == "category-entry") {
    $title = "This category page is {$page->title}";
  }
  else {
    // get the current page alt page title field (first) or
    // if empty/doesn't exist, the current page title field
    $title = $page->get("altTitle|title");
  }
?>

<header>
  <h1><?= $title; ?></h1>
</header>

Feedback & support

I hope you enjoyed this tutorial. You can support pwtuts by following on @pwtuts.

Related tutorials / See all