Building fullstack websites with WordPress and PHP
Hello! So I've actually got around to start writing something kinda technical. Which is great because I've just been posting depressing stuff non stop. Anyway... time to get into the meat and potatoes.
First things first, let's establish what fullstack means. Just in case anyone is wondering. So there's two sides to a web app or program really... The front end and the backend. Frontend programming involves user interfaces and interactions. The backend is everything that the user doesn't see but is very important, it's the business logic behind the app. When someone mentions "fullstack" anything, they're talking about doing both the front and back ends of the app. There's no stack of pancakes involved.
Many people on the internet, probably someone with a huge beard, will be screaming at me on why I would ever use WordPress as a base for software development. I want to explain that real quick. First off, it's a very easily modifiable frontend used by blogs, businesses, and stores. I might not use it for my blog, but don't let that stop you from using it. It can be a little awkward if you're not used to PHP or SQL programming but is easy enough to pick up and figure out. The documentation for it is rich, with a vibrant community who're ready to help. The age of WordPress also helps to, but watch out for old tutorials.
So first things first, you need a local development environment to get started. We could go into making a LAMP (Linux, Apache, MySQL, PHP) server on a virtual machine. You could even build your own computer for that purpose. I'm not getting into that and will be focusing on the development but if you want to get started really fast, I'd suggest you look up Local by FlyWheel. If you're using Linux, I'd have you look into how to make a virtual machine with VirtualBox, VMWare, or some other virtualization solution that exists on the internet and install LAMP (Linux, Apache, MySQL, PHP) on it.
Local by FlyWheel, is actually an automated environment to develop and even deploy WordPress sites. I use it for primarily for development purposes and will be telling you quickly how to get started. When you download the program and install the program, open it and create a new site. You can use the default settings. It doesn't matter really where you store the site as long as you can find it. By default it should be in the root of your user folder or home directory under the name "Local Sites". Once you created the site, start the virtual machine, and navigate to the directory in your favorite text editor. I recommend Visual Studio Code, Atom, or Sublime Text.
Once you are there, you will need a basic theme to work off of. I recommend HTML5 blank for WordPress. It has all the basics in a simple template you can stylize to your liking. It also gives you a video to learn how to convert a HTML/CSS mockup into a theme you can dynamically use, I really recommend watching it. Once you have the theme installed, you can start modifying it with your editor. If you're using Visual Studio Code, I'd build a workspace linking the theme folder in it's installed location (app\public\wp-content\themes\theme). You'll be adding more folders soon.
Now for stylization! So the template comes with a CSS file you can modify immediately. But you can also install Bootstrap or some other GUI framework to help you design and program your site. To do that, you need to "register" and "enqueue" the scripts and stylesheets in the "functions.php" file. I'd get really familiar with this file and learn what everything is. Luckily the file is well commented, and will explain what almost every line does so you can modify it to your liking. Once you have your scripts and styles registered and enqueued, check to see if the local website actually loads those files you tried to register. You should always try to use the ".min" or minified versions of the JavaScript and CSS files. Use the regular versions if you want more debugging help.
Now we can design the site as you please. keeping in mind that the files you need to modify are templates. Go to "footer.php" if you want to modify the footer, and "header.php" for the header. You also have the "author", "archive", "category", "comment", "index", "loop", "page", "pagination", "search", "searchform", "sidebar", "single", and "tag" to modify to your liking. You should try to test each one before we start making things really interactive and functional. WordPress uses these files as templates to pragmatically display content. Once you get started on the design, changing it might be painful down the line. If you're having issues with getting a good navigation menu working, don't be afraid to use someone elses work to get started. If you're using bootstrap, I would recommend WP Bootstrap Navwalker. Looking at other currently existing themes for inspiration is cool, just don't steal it and claim it as your own.
Now that you modified the site to look like you want it to. Let's dive into backend programming with plain PHP. Because WordPress takes over quite a bit to render stuff on the server in PHP, I would use a subdirectory under the "app\public" folder... aptly named "backend".
So if you've ever worked with other backend frameworks. You probably don't want to intercept HTTP calls, figure out the route, and call a specific function on that route... So I'd recommend getting a router. But first, we need to install Composer. Composer is a package dependency manager for PHP. We will be using it to install various things needed for backend programming (like a router). Once you have Composer installed, create a folder called, "composer.json" in the backend directory I had you create earlier. This is the settings file for the dependencies and it will help manage the versions of packages installed in the vendor folder. To read more on how the basic usage works, go here. Going to Packagist is recommended if you want to find packages to install with the "install" command that could help you on your journey.
For the purposes of this tutorial, look up bramus/router, and install it. You could ignore me and use Laravel, but I like to use bramus/router because it's lighter. We will be using this to create the backend like you would with any other kind of framework. I would get familiar with the documentation but it's easy enough to figure out. You create a router, and you attach route handlers to it that get called. This is necessary if you plan on making an API (Application Programming interface). If you're unfamiliar with APIs in general... look up REST, SOAP, and other ways to program APIs. I favor REST centric design because it makes sense to me. You may program your routing structure however you like, but understand you will be playing with the data on the website in JavaScript and it needs to make some sense.
So to get started on programming the backend, create the "index.php" file we will use to route all traffic to. There we can pragmatically handle requests. If you wanted to create a user model for your database, you can use WordPress's instead. "wp_get_current_user" and "wp_create_user" are immensely useful and can be called from the backend... because it's just a subdirectory and not a subdomain or something. Adding the following code to the top of the index.php file....
require_once dirname(**FILE**) . "/../wp-config.php";
require_once dirname(**FILE**) . "/../wp-blog-header.php";
Will actually give you access to various parts of the WordPress backend to let you piggy back off of. You need to adopt much of the methodologies the WordPress system uses. I would avoid making custom post types for end users. For every route you make, check to see if the user is logged in and authenticated before you do anything important. You don't want anonymous users creating entries in your database. Letting them read or search redacted database entries might be your desired goal though.
NOTE: UserID's are numerical and are actually pretty decent for use with keeping track of ownership of database entries. You might want to invest more interest in user ownership if you want something more advanced than just an array of users who have read/write permission.
You might not notice yet, but you also need an ".htaccess" file to direct traffic to your index.php file.
{% highlight console %}
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . index.php [L]
Once added... every time you access the backend subdirectory for your site, you will be calling the index.php file and then the appropriate route. Creating individual files for each model and controller is recommended but you can write the entire backend into index.php if you wanted. I use an object oriented approach where the class handles a copy of the original data, and the modified data that will be applied to the database. There's even a static method I call on the model class that registers the router by passing it as a function.
// User.php
class User extends Model {
/* Other method and properties for User */
public static function setup_router($router) {
/* Other route handlers */
$router->get("/User/([\d|\w]+)", function (string $uid) {
set_headers();
$user = wp_get_current_user();
$response = null;
if (isset($uid)) {
$response = User::find_by_id($uid);
} else {
return send_error("Missing uid", $uid);
}
if ($response->hasPermission($user->ID) == false) {
return send_error("Not allowed.");
}
return send_response("Found user.", $response);
});
/* More route handlers */
}
}
// Index.php
User::setup_router(\$router);
You can repeat this process for each model you think you'll need. I really recommend making a base class called Model or something that will handle most of the boiler plate stuff... Saving, removing, searching, maybe permission handling. If you want help programming with SQL. I like to use Medoo. It has a very NoSQL like way of handling SQL. It uses an easy search language like you would find using MongoDB or MongooseJS on NodeJS... So easy, you can use the search language over a HTTP request and lose none of the functionality. You also don't have to worry about SQL injection and it has a nifty type system that can serialize JSON and basic types automatically. It could take some getting used to if you ever used NoSQL first, like me, but it's pretty intuitive. It's small. Compatible with most SQL servers, like MySQL, SQLite, and PostgreSQL.
Once you built up the backend some, or at least have it designed. We can start working on the JavaScript that melds with the backend. This is actually pretty easy in my opinion compared to the rest of the post. Go back to the theme and create some JavaScript files under the js directory or something. You just need to enqueue the script inside functions.php and call the JavaScript code from the individual pages.
When creating the JavaScript framework, try to use jQuery AJAX requests. WordPress uses this internally and it would make sense to do the same. I created classes for each model, and of course a boiler plate class for Model. Each class should have a way to save, remove, and find entries in the database.
You can barrow my Model class as a base. It's not super fleshed out or nice but it's what I use for my current project.
/// <reference path ="../node_modules/@types/jquery/index.d.ts"/>
"use strict";
export default class Model {
static get ModelName() {
return "Model";
}
static get ModelUIDName() {
return "";
}
static get ModelNamePlural() {
return "Models";
}
static ModelQuery() {
return null;
}
static AllowedNames() {
return ["dateCreated", "date_created", "lastModified", "last_modified"];
}
static CacheSave() {
if (typeof localStorage !== "undefined") {
var items = Array.from(Model.ModelCache.entries());
var data = [];
items.forEach(([key, item]) => {
if (
key !== "" &&
typeof key === "string" &&
item &&
typeof item.toObject === "function"
) {
data.push([key, Date.now(), item.toObject()]);
}
});
localStorage.setItem("ModelCache", JSON.stringify(data));
}
}
static CacheLoad() {
var ONE_DAY = 24 * 60 * 60 * 1000; /* ms */
var dayLess = new Date(Date.now() - ONE_DAY);
if (typeof localStorage !== "undefined") {
var json = localStorage.getItem("ModelCache");
if (typeof json === "string" && json !== "") {
try {
var data = JSON.parse(json);
var items = [];
data.forEach(([key, unixTime, item]) => {
var dateCached = new Date(unixTime);
/** @type any */
var ModelClass = window[item.ModelName];
if (item.ModelName === "Location" && window["LocationModel"]) {
ModelClass = window["LocationModel"];
}
if (ModelClass && item && key && dayLess < dateCached) {
items.push([key, new ModelClass(item)]);
}
});
Model.ModelCache = new Map(items);
} catch (e) {
Model.ModelCache = new Map();
}
}
}
}
static CacheFindByProp(name, value) {
for (var key of Model.ModelCache.keys()) {
var item = Model.ModelCache.get(key);
if (item) {
for (var propertyName in item) {
var prop = item[propertyName];
if (propertyName == name) {
if (prop === value) {
return item;
} else if (new RegExp(`${value}.*`, "gi").test(prop)) {
return item;
}
}
}
}
}
return null;
}
static CacheFindByPlaceName(place_name) {
return Model.CacheFindByProp("place_name", place_name);
}
static CacheFindByName(name) {
return Model.CacheFindByProp("name", name);
}
static CacheFindByUID(uid) {
for (var key of Model.ModelCache.keys()) {
var item = Model.ModelCache.get(key);
var { ModelUIDName } = item.constructor;
if (item && item[ModelUIDName] && item[ModelUIDName] === uid) {
return item;
}
}
return null;
}
static SearchCacheInit() {
Model.CacheLoad();
setInterval(() => {
Model.CacheSave();
}, 10000);
}
static SearchCacheGet(term, modelName) {
var result = [];
Model.ModelCache.forEach((item) => {
var termRegex = new RegExp(`${term}.*`, "gi");
if (item) {
var { place_name, name, constructor } = item;
var { ModelName } = constructor;
if (
name &&
name.search(termRegex) !== -1 &&
(!modelName || ModelName == modelName)
) {
result.push(item);
} else if (
place_name &&
place_name.search(termRegex) !== -1 &&
(!modelName || ModelName == modelName)
) {
result.push(item);
}
}
});
return result;
}
get dateCreated() {
return this.getProp("dateCreated");
}
get lastModified() {
return this.getProp("lastModified");
}
constructor(data = {}) {
this._data = Object.assign({}, data);
this._changes = {};
}
hasProperty(name) {
var allowedNames = this.constructor["AllowedNames"]();
for (var aName of allowedNames) {
if (aName == name) {
return true;
}
}
return false;
}
toObject() {
return Object.assign(
{
ModelName: this.constructor["ModelName"],
},
this._data,
this._changes
);
}
/**
* @param {string | number} key
* @param {any} value
*/
setProp(key, value) {
if (this._data[key] !== value) {
this._changes[key] = value;
}
}
/**
* @param {string | number} key
* @param {any} defaultValue
*/
getProp(key, defaultValue = undefined) {
if (this._changes[key] !== undefined) {
return this._changes[key];
}
if (this._data[key] !== undefined) {
return this._data[key];
}
console.log(key, this);
return defaultValue;
}
/**
* @param {string | number} key
*/
delete(key) {
if (typeof this._changes[key] != "undefined") {
delete this._changes[key];
}
}
/**
* @returns {Promise<this>} promise itself
*/
save() {
var self = this;
var ModelName = this.constructor["ModelName"];
var ModelUIDName = this.constructor["ModelUIDName"];
return new Promise((resolve, reject) => {
if (ModelName == "Model")
return reject(new Error("ModelName not overriden"));
self._changes["lastModified"] = Date.now();
var changes = Object.assign({}, self._changes);
/**@type FormData|object */
var form = new FormData();
var commandPath = `/backend/${ModelName}`;
var commandType = "POST";
var processData = false;
/**@type string|boolean */
var contentType = false;
Object.keys(changes).forEach((key) => {
form.set(key, changes[key]);
});
form.delete("files");
if (typeof self._data["dateCreated"] != "undefined") {
commandType = "PUT";
commandPath = `/backend/${ModelName}/${self[ModelUIDName]}`;
if (form.get("icon") !== "") form.delete("icon");
var object = {};
form.forEach((value, key) => {
object[key] = value;
});
form = JSON.stringify(object);
}
jQuery.ajax({
url: commandPath,
type: commandType,
processData,
contentType,
data: form,
success: (response) => {
self._changes = {};
Model.ModelCache.set(self[ModelUIDName], self);
resolve(self.assignData(response.value.data));
},
error: (response) => {
reject(response);
},
});
});
}
/**
* @returns {Promise<this>} this or itself
*/
remove() {
var self = this;
var ModelName = this.constructor["ModelName"];
var ModelUIDName = this.constructor["ModelUIDName"];
return new Promise((resolve, reject) => {
if (ModelName == "Model")
return reject(new Error("ModelName not overriden"));
if (typeof this._data["dateCreated"] == "undefined")
return reject(new Error("Not saved, no need to remove"));
var commandPath = `/backend/${ModelName}/${self[ModelUIDName]}`;
var commandType = "DELETE";
jQuery.ajax({
url: commandPath,
type: commandType,
success: (data) => {
Model.ModelCache.delete(self[ModelUIDName]);
resolve(self);
},
error: (response) => {
reject(response);
},
});
});
}
static findOne(ModelClass, criteria, noThrow) {
var ModelName = ModelClass["ModelName"];
var commandPath = `/backend/${ModelName}/findOne`;
var ModelUIDName = ModelClass.constructor["ModelUIDName"];
return new Promise((resolve, reject) => {
jQuery.ajax({
url: commandPath,
type: "GET",
data: criteria,
success: (response) => {
if (response && response.value && response.value.data) {
var item = new ModelClass(response.value.data);
Model.ModelCache.set(item[ModelUIDName], item);
resolve(item);
} else {
reject(
new Error(
`No usefull response returned: ${JSON.stringify(response)}`
)
);
}
},
error: noThrow ? () => resolve([]) : reject,
});
});
}
static findMany(ModelClass, criteria, noThrow) {
var ModelName = ModelClass["ModelName"];
var commandPath = `/backend/${ModelName}/findMany`;
var ModelUIDName = ModelClass.constructor["ModelUIDName"];
return new Promise((resolve, reject) => {
jQuery.ajax({
url: commandPath,
type: "GET",
data: criteria,
success: (response) => {
if (Array.isArray(response.value)) {
resolve(
response.value.map((item) => {
var model = new ModelClass(item.data);
Model.ModelCache.set(model[ModelUIDName], model);
return model;
})
);
} else {
reject(new Error("Response is not a array"));
}
},
error: noThrow ? () => resolve([]) : reject,
});
});
}
/**
* @param {object} data
* @returns {this} this or itself
*/
assignData(data = {}) {
this._data = Object.assign(this._data, data);
return this;
}
setUpload(name, value) {
var self = this;
var ModelName = this.constructor["ModelName"];
var ModelUIDName = this.constructor["ModelUIDName"];
return new Promise((resolve, reject) => {
var fType = typeof value;
var nType = typeof name;
if (nType !== "string") {
return reject(
new Error(`Name is a ${nType}(${name}) and not a string`)
);
} else if (fType !== "object") {
return reject(
new Error(`File is a ${fType}(${value}) and not an object`)
);
} else if (value !== null) {
var form = new FormData();
form.set(name, value);
jQuery.ajax({
url: `/backend/${ModelName}/${self[ModelUIDName]}/${name}`,
type: "POST",
contentType: false,
processData: false,
cache: false,
data: form,
success: (response) => {
self.assignData(response.value.data);
resolve(self);
},
error: (response) => reject(response),
});
}
});
}
/**
* @param {object} changes
* @returns {this} this or itself
*/
update(changes = {}) {
var allowedNames = this.constructor["AllowedNames"]() || [];
if (changes instanceof FormData) {
var copy = {};
for (var key of changes.keys()) {
if (this.hasProperty(key)) copy[key] = changes.get(key);
}
changes = copy;
}
Object.assign(this._changes, changes);
return this;
}
static split(val) {
return val.split(/,\s*/);
}
static extractLast(term) {
var terms = Model.split(term);
return terms.pop();
}
static async autocompleteSource(ModelClass, multiple, request, response) {
var term = multiple ? Model.extractLast(request.term) : request.term;
var newItems = await Model.findMany(
ModelClass,
ModelClass.ModelQuery(term),
true
);
newItems.forEach((item) => {
var uid = item[item.constructor.ModelUIDName];
Model.ModelCache.set(uid, item);
});
console.log(newItems);
return response(
newItems.map((item) => ({
id: item[item.constructor.ModelUIDName],
label: item.name,
value: item.name,
model: item,
}))
);
}
static autocompleteSearch(multiple, nameInput) {
var value = nameInput.val();
if (multiple) {
var term = Model.extractLast(value);
if (term.length < 1) {
return false;
}
}
if (value.length < 1) {
return false;
}
return true;
}
static autocompleteSelect(multiple, nameInput, idIput, _event, ui) {
if (multiple === true) {
var { label, id: uid } = ui.item;
var value = nameInput.val();
var terms = Model.split(value);
var current = null;
try {
current = JSON.parse(idIput.val()) || [];
} catch (error) {
current = [];
}
if (current.find((item) => item === uid) == null) {
current.push(uid);
// remove the current input
terms.pop();
// add the selected item
terms.push(label);
// add placeholder to get the comma-and-space at the end
terms.push("");
nameInput.val(terms.join(", "));
idIput.val(JSON.stringify(current));
} else if (current.length !== 1) {
var terms = Model.split(value);
// remove the current input
terms.pop();
terms.push("");
nameInput.val(terms.join(", "));
} else {
terms = [ui.item.value];
nameInput.val(terms.join(", "));
}
return true;
} else {
nameInput.val(label);
idIput.val(uid);
return true;
}
}
static autocomplete(ModelClass, nameInput, idIput, multiple = false) {
if (!ModelClass || !nameInput || !idIput) return;
if (typeof nameInput.autocomplete !== "function") return;
var autoC = nameInput.autocomplete({
source: Model.autocompleteSource.bind(this, ModelClass, multiple),
search: Model.autocompleteSearch.bind(this, multiple, nameInput),
select: Model.autocompleteSelect.bind(this, multiple, nameInput, idIput),
});
autoC.autocomplete("instance")._renderItem = function (ul, item) {
var RenderItemFunc = item.model.constructor.renderItem || null;
if (RenderItemFunc) {
return RenderItemFunc(ul, item);
}
return $("<li>").append(`<div>${item.label}</div>`).appendTo(ul);
};
}
}
Model.ModelCache = new Map();
I even include a little goody for jQuery-autocomplete and basic caching that probably needs some fixing. It's not the most intuitive thing in the world but it's more of a head start. Sorry, I'm not giving you the backend version of my Model class because it's "proprietary." I don't want to give anyone a upper hand on hacking my databases by knowing how I do everything.
Anyway... now that you have all the models fleshed out (more or less) on the frontend. You can start building pages. Go back to functions.php and add the following function... we're going to use it to register the pages pragmatically so you don't have to do it manually.
<?php
function ensure_exists($slug) {
if(get_page_from_slug($slug) == null) {
$post_details = array(
"post_title" => ucwords(str_replace("-", " ", $slug)),
"post_content" => "",
"post_status" => "publish",
"post_author" => 1,
"post_type" => "page"
);
wp_insert_post( \$post_details );
}
}
add_action("wp_loaded", "create_pages"); // Create initial pages.
function create_pages() {
ensure_exists("example") // Creates a page called example
ensure_exists("example 2") // Creates a page called example-2
}
?>
When the website loads, it will create the pages in the database. Now to program those pages. Copy the contents you created for "page.php" and copy it to a file called, "page-*name-of-page*.php"... If you made a page called "example", you would create a file called "page-example.php" in the theme folder. We're using the "page.php" template as a base and will start doing custom pages with it. Replace " php<?php the_content(); ?>" with custom html code. You can shoehorn in some JavaScript with a script tag. You can even statically generate data you plan on rewriting when the page loads... Like how ReactJS does things... kinda. Except you'd be using jQuery to update the content. If you want to avoid load issues, use the following code to check to see if the document is ready before edit.
?>
<script>
jQuery(document).ready(() => {
/* Do code here*/
});
</script>
<?php
If you want to create dialogs pop ups. Create a separate PHP file that has the HTML and JavaScript to open it. Then require it on pages that use it. I'm including my "Success" dialog popup code to help as an example. "openSuccessDialog" is available on the window object in the browser, so it's a global function that can be called. You pass a message, label, and close callback to it for language translations, and interactivity.
<div
class="modal fade"
id="success_modal_dialog"
tabindex="-1"
role="dialog"
aria-labelledby="success_modal_dialog_label"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="bg-dark modal-content">
<div class="modal-header">
<h5 class="modal-title" id="success_modal_dialog_label"><?php _e("Success"); ?></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<span id="success_modal_dialog_message"></span>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal"><?php _e("Close"); ?></button>
</div>
</div>
</div>
</div>
<script>
jQuery(document).ready(() => {
var SuccessModal = jQuery("#success_modal_dialog");
var SuccessModalLabel = jQuery("#success_modal_dialog_label");
var SuccessModalMessage = jQuery("#success_modal_dialog_message");
async function openSuccessDialog(label, message, onClose) {
SuccessModal.modal();
SuccessModalLabel.html(label);
SuccessModalMessage.html(message);
if(typeof onClose === "function")
SuccessModal.on('hidden.bs.modal', onClose);
}
if(typeof window.openSuccessDialog !== "function") {
window.openSuccessDialog = openSuccessDialog;
}
});
</script>
I'm probably going to come back to this post and update it some. I might even create a boiler plate GitHub repository to be supplemental. Working with PHP & WordPress has it's advantages. PHP is slightly faster than using NodeJS, ASP.Net, or Java to do full stack development. Sure, PHP is an ugly language but it's still useful and intuitive enough to use. If you keep pounding away at the design and implementation, you will eventually have something that look more like a web app than a WordPress site. Which is actually cool. You can take advantage of the admin area pages to change API keys, create custom admin pages, and create blog posts or pages explaining how your app works. You can even have multi-language support. It's oddly amazing to use WordPress as a frontend and backend because it's so extensible and hackable.
I want to note there's more you need to do and learn yourself. Like adding the SQL table, it's columns, and permissions. If I told you how to do everything that wouldn't be any fun and you'd have little incentive to hire someone like me. If you want to ask me questions, my email is always open.