concrete5 also supports the loading of Page
objects by the path that is displayed in the web browser. This is a convenient way to load pages without knowing their numerical ID. In this exercise, we will load an About Us page by its path.
We will be loading a page with the path of /about-us
. If this page does not exist in your concrete5 site, please add it to the sitemap before attempting this exercise.
Using a static function called getByPath
, we can easily get a Page
object without knowing the ID. The steps are as follows:
Open the
/config/site-post.php
file in your code editor.Declare the path of the page that you wish to load.
$path = '/about-us';
We can load the page located at
http://example.com/about-us
by passing the path string to thegetByPath
function.$aboutPage = Page::getByPath($path);
To make sure we grabbed the correct page, dump the
$aboutPage
variable to verify that we have a fully loadedPage
object. We will use the custom debug function that we created in the chapter introduction.my_debug($aboutPage);
concrete5 will query the database for the page that has the specified path assigned to it. You will want to use good judgment when loading pages by their paths, as that data can change easily through the concrete5 interface. Imagine that you are working on a site with 15 editors, and any one of them has the ability to edit the path of a page. concrete5 by default will save old page paths whenever a new one is changed, but it is not required. Hard coding page paths in your custom applications should be used only when appropriate. It is a much better idea to load pages by their ID whenever possible, as that ID does not change.
You can load any page on the site using this technique. To load a Careers
page that exists below the About
page that we just loaded, you would write the following:
$careersPage = Page::getByPath('/about-us/careers');
You should know that concrete5 will cache the page IDs related to each path, so if you are experiencing unexpected results while using this function, make sure to clear your site cache by visiting /dashboard/system/optimization/clear_cache/
on your concrete5 website.