How to create a simple WordPress like route template - leija.io
  • @undefined- Jul 8

    How to create a simple WordPress like route template

    This is going to be a quick 2 minute tutorial. Today we’ll build a simple WordPress like route template system.

    The goal is to look at the URL, and serve it a PHP template file. Let’s get started!

    Step 1

    In the root of your project, create a .htaccess file. Inside the .htaccess file add these lines of code.

    Gist url: https://gist.github.com/rleija703/9101cd857c9280f24bb64f368da4dcb5

    This will ensure that all requests are sent to index.php.

    Step 2

    Create your index.php file in the root of the project and add these lines of code:

    Gist url: https://gist.github.com/rleija703/811aa3df5e0efa90646fda59894f6f01

    In line 2, PHP is grabbing the server request URI and converting it into an array with a max of 2 array elements.

    In line 4 we’re doing an if check to see if it meets a specific value to return a specific view template. This can work well for web pages such as the about page where the path is typically /about, etc.

    In line 6, we’re using RegEx to see if the URL matches a unique pattern to return the appropriate view template. This is good for URLs that are interior pages and follow a multiple path segment pattern such as:

    • /news/article1
    • /news/article3

    RegEx can be intimidating and very confusing. I used this tool to make it easier for me and help me validate my RegEx.