Hello World Master

Tutorials, articles and quizzes on Software Development

PHP > Articles

Import HTML templates from separate file for custom WordPress plugin

This article is associated with the following tutorial series

Building a basic plugin in WordPress

As we make our pages more complex we might want have our views to more things, so it would be easier to split them out into their own file.

Create a new folder for our templates

First what we want to do is create a folder called templates, which will contain PHP files containing our templates. The templates folder will be located in the root of our plugin

The files are PHP files instead of HTML files because we need to import our templates into the PHP file we’re taking them. The end result will be importing a PHP file into another PHP file.

Copy our existing templates over to our templates folder

Lets copy over the HTML string we had in the VictoryflameView function in our View class. Make sure to remove the quotes

<h1> I am the page your menu directed you to </h1>

in templates/VictoryflameView.php

and

<h1> Submenu </h1>

in templates/SubmenuView.php

Update your View class to import their templates

To use the templates in our template folder, we need to replace the string of HTML we echo in the functions of our view class to require our templates in their location. We do this with require_once

Next we need pass in the path of our WordPress Plugin. We do this using the following functions

  • plugin_dir_path
  • dirname

We pass in the dirname function with parameters or __FILE__ and 1, since we want the location thats one level above the current directory. then we append our dirname call to the location of our template in the root of our plugin

<?php

  namespace Inc;

  class View {

    public function VictoryflameView() {
      return require_once( plugin_dir_path( dirname( __FILE__, 1 ) ) . "templates/VictoryflameView.php" );
    }

    public function SubmenuView() {
      return require_once( plugin_dir_path( dirname( __FILE__, 1 ) ) . "templates/SubmenuView.php" );    
    }

  }