Wordless’s documentation¶

Introduction¶
Wordless is an opinionated WordPress plugin + starter theme that dramatically speeds up and enhances your custom theme creation. Some of its features are:
- A structured, organized and clean theme organization
- Scaffold a new theme directly within wp-cli
- Write PHP templates with the Pug templating system
- Write CSS stylesheets using the awesome SCSS syntax
- Write Javascript logic in ES2015
- A growing set of handy and documented PHP helper functions ready to be used within your views
- Preconfigured support to MailHog mail-catcher.
- Development workflow backed by WebPack, BrowserSync (with live reload), WP-CLI, Yarn. All the standards you already know, all the customizations you may need.
Contents¶
Installation¶
Wordless GEM (favourite)¶
The quickest CLI tool to setup a new WordPress locally. Wordless ready.
No prerequisites. Just joy.
Navigate to https://github.com/welaika/wordless_gem to discover the tool and set up all you need for local development. In less than 2 minutes ;)
If you already have a WordPress installation and just want to add Wordless to it, read the following paragraph.
(Not so) Manual¶
At the end of the installation process you will have
- a plugin - almost invisible: no backend page, just
wp-cli
commands - a theme - where you will do all of the work
Prerequisites¶
- Node. Depending on the Wordless version you’ll need a specific Node version. Read more at Nodejs page.
- WP-CLI http://wp-cli.org/#installing
- Global packages from NPM:
npm install -g foreman yarn
[1] [2] - WordPress installed and configured as per official documentation
- Composer
brew install composer
- If you’d like to enable the mail-catcher while developing, install MailHog.
On MacOS this is as simple as
brew install mailhog
. Wordless will do the rest.
Note
We don’t know if you have a local apache {M,L,W}AMPP instance or whatever in order to perform the official installation process. Keep in mind that Wordless’s flow does not need any external web server, since it will use the wp server command to serve your wordpress.
See also
See also
Steps¶
Note
We consider that you have WordPress already up and running and you are in the project’s root directory in your terminal.
Install and activate the wordpress plugin
wp plugin install --activate wordless
Scaffold a new theme
wp wordless theme create mybrandnewtheme
See also
CLI for info about wp-cli integration
Enter theme directory
cd wp-content/themes/mybrandnewtheme
Setup all the things
yarn setup
Start the server - and the magic
yarn run server
Webpack, php server and your browser will automatically come up and serve your needs :)
Acceptance tests¶
To run acceptance test suite start the test server in one terminal
yarn test:server
and in another terminal let’s actually run tests:
yarn test
See also
Development environment to understand how the magic works
Note
It is possible that your OS asks you to allow connections on server ports (3000 and/or 8080). It’s just ok to do it.
[1] | https://www.npmjs.com/package/yarn |
[2] | https://www.npmjs.com/package/foreman |
Usage¶
Theme anatomy¶
This is a typical Wordless theme directory structure:
your_theme_dir
├── config/
│ ├── initializers/
│ └── locales/
├── dist/
│ ├── fonts/
│ ├── images/
│ ├── javascripts/
│ ├── stylesheets/
│ └── README.md
├── helpers/
│ └── README.mdown
├── node_modules/
├── src/
│ ├── images/
│ ├── javascripts/
│ ├── stylesheets/
│ └── main.js
├── tmp
│ └── .gitkeep
├── views
│ ├── layouts
│ └── posts
├── .browserslistrc
├── .env
├── .gitignore
├── .nvmrc
├── .stylelintignore
├── .stylelintrc.json
├── Procfile
├── index.php
├── package.json
├── release.txt
├── screenshot.png
├── style.css
├── webpack.config.js
├── webpack.env.js
└── yarn.lock
Now let’s see in detail what is the purpose of all those directories.
Routing¶
The index.php serves as a router to all the theme views.
<?php
if (is_front_page()) {
render_view("static/homepage)");
} else if (is_post_type_archive("portfolio_work")) {
render_view("portfolio/index");
} else if (is_post_type("portfolio_work")) {
render_view("portfolio/show");
}
As you can see, you first determine the type of the page using WordPress conditional tags, and then delegate the rendering to an individual view.
See also
render_view() helper documentation
See also
Using Page Template Wordpress’ feature inside Wordless
Rendering¶
render_view()¶
The main helper function used to render a view is - fantasy name - render_view()
. Here is its signature:
<?php
/**
* Renders a view. Views are rendered based on the routing.
* They will show a template and a yielded content based
* on the page requested by the user.
*
* @param string $name Filename with path relative to theme/views
* @param string $layout The template to use to render the view
* @param array $locals An associative array. Keys will be variable
* names and values will be variable values inside
* the view
*/
function render_view($name, $layout = 'default', $locals = array()) {
/* [...] */
}
Thanks to this helper, Wordless will always intercept PUG files and automatically translate them to HTML.
Note
Extension for $name
can always be omitted.
See also
PHUG section @ Code compilation
Inside the views
folder you can scaffold as you wish, but you’ll have
to always pass the relative path to the render function:
<?php
render_view('folder1/folder2/myview')
The $locals
array will be auto-extract()
-ed inside the required view, so you can do
<?php
render_view('folder1/folder2/myview', 'default', array('title' => 'My title'))
and inside views/folder1/folder2/myview.pug
h1= $title
render_partial()¶
render_partial()
is almost the same as its sister render_view()
, but it does
not accept a layout as argument. Here is its signature:
<?php
/**
* Renders a partial: those views followed by an underscore
* by convention. Partials are inside theme/views.
*
* @param string $name The partial filenames (those starting
* with an underscore by convention)
*
* @param array $locals An associative array. Keys will be variables'
* names and values will be variable values inside
* the partial
*/
function render_partial($name, $locals = array()) {
$parts = preg_split("/\//", $name);
if (!preg_match("/^_/", $parts[sizeof($parts)-1])) {
$parts[sizeof($parts)-1] = "_" . $parts[sizeof($parts)-1];
}
render_template(implode($parts, "/"), $locals);
}
Partial templates – usually just called “partials” – are another device for breaking the rendering process into more manageable chunks.
Note
Partials files are named with a leading underscore to distinguish them from regular views, even though they are referred to without the underscore.
Layouts¶
views/layouts
directory
When Wordless renders a view, it does so by combining the view within a layout.
E.g. calling
render_view('folder1/folder2/myview')
will be the same as calling
render_view('folder1/folder2/myview', 'default', array())
so that the default.html.phug
layout will be rendered. Within the layout,
you have access to the wl_yield()
helper, which will combine the required
view inside the layout when it is called:
doctype html
html
head= render_partial("layouts/head")
body
.page-wrapper
header.site-header= render_partial("layouts/header")
section.site-content= wl_yield()
footer.site-footer= render_partial("layouts/footer")
- wp_footer()
Note
For content that is shared among all pages in your application that use the same layout, you can use partials directly inside layouts.
Views¶
views/**/*.pug
orviews/**/*.php
This is the directory where you’ll find yourself coding most of the time. Here you can create a view for each main page of your theme, using Pug syntax or plain HTML.
Feel free to create subdirectories to group together the files. Here’s what could be an example for the typical WordPress loop in an archive page:
// views/posts/archive.html.pug
h2 Blog archive
ul.blog_archive
while have_posts()
- the_post()
li.post= render_partial("posts/single")
// views/posts/_single.html.pug
h3!= link_to(get_the_title(), get_permalink())
.content= get_the_filtered_content()
Wordless uses Pug.php - formerly called Jade.php - for your Pug views, a great PHP port of the PugJS templating language. In this little snippet, please note the following:
- The view is delegating some rendering work to a partial called
_single.html.pug
- There’s no layout here, just content: the layout of the page is stored in a
secondary file, placed in the
views/layouts
directory, as mentioned in the paragraph above - We are already using two of the 40+ Wordless helper functions,
link_to()
andget_the_filtered_content()
, to DRY up this view - Because the
link_to
helper will return html code, we used unescaped buffered code to print PUG’s function:!=
. Otherwise we’d have obtained escaped html tags.
It looks awesome, right?
Helpers¶
helpers/*.php
files
Helpers are basically small functions that can be called in your views to help keep your code stay DRY. Create as many helper files and functions as you want and put them in this directory: they will all be required within your views, together with the default Wordless helpers. These are just a small subset of all the 40+ tested and documented helpers Wordless gives you for free:
lorem()
- A “lorem ipsum” text and HTML generatorpluralize()
- Attempts to pluralize wordstruncate()
- Truncates a given text after a given lengthnew_post_type()
andnew_taxonomy()
- Help you create custom posts and taxonomydistance_of_time_in_words()
- Reports the approximate distance in time between two dates
Our favourite convention for writing custom helpers is to write 1 file per
function and naming both the same way. It will be easier to find with `cmd+p
😉
Initializers¶
config/initializers/*.php
files
Remember the freaky functions.php
file, the one where you would drop every
bit of code external to the theme views (custom post types, taxonomies,
wordpress filters, hooks, you name it?) That was just terrible, right?
Well, forget it.
Wordless lets you split your code into many modular initializer files, each one with a specific target:
config/initializers
├──── backend.php
├──── custom_gutenberg_acf_blocks.php
├──── custom_post_types.php
├──── default_hooks.php
├──── hooks.php
├──── login_template.php
├──── menus.php
├──── shortcodes.php
├──── thumbnail_sizes.php
- backend: remove backend components such as widgets, update messages, etc
- custom_gutenbers_acf_blocks: Wordless has built-in support to ACF/Gutenberg blocks. Read more at ACF Gutenberg Blocks
- custom_post_types: well… if you need to manage taxonomies, this is the place to be
- default_hooks: these are used by wordless’s default behaviours; tweak them only if you know what are you doing
- hooks: this is intended to be your custom hooks collector
- menus: register new WP nav_menus from here
- shortcodes: as it says
- thumbnail_sizes: if you need custom thumbnail sizes
These are just some file name examples: you can organize them the way you prefer. Each file in this directory will be automatically required by Wordless.
Locale files¶
config/locales
directory
Just drop all of your theme’s locale files in this directory. Wordless will take care of calling load_theme_textdomain() for you.
Note
Due to the WordPress localization framework, you need to append our
"wl"
domain when using internationalization. For example, calling
__("News")
without specifying the domain will not work.
You’ll have to add the domain “wl” to make it work:
__("News", "wl")
Assets¶
The Fast Way¶
- write your SCSS in
src/stylesheets/screen.scss
- write your JS in
src/javascripts/application.js
and all will automagically work! :)
I need to really understand¶
Wordless has 2 different places where you want to put your assets (javascript, css, images):
- Place all your custom, project related assets into
src/*
- Since you are backed by Webpack, you can use NPM (
node_modules
) to import new dependencies following a completely standard approach
They must be placed inside src/javascript/
and
src/stylesheets/
and src/images/
.
They will be compiled and resulting compilation files will be moved in the corresponding
assets/xxx
folder.
Compilation, naming and other logic is fully handled by webpack.
Images will be optimized by ImageminPlugin. The default setup already translates
url
s inside css/scss files in order to point to images in the
right folder.
Take a look to the default screen.scss
and application.js
to see
usage examples.
See also
See also
You can use node modules just as any SO answer teaches you :)
Add any vendor library through YARN with
yarn add slick-carousel
Then in your Javascript you can do
require('slick-carousel');
or if the library exports ES6 modules you can do
import { export1 } from "module-name";
and go on as usual.
Test Suite¶
The default Wordless theme is shipped with preconfigured test suite.
The test suite is implemented using the awesome WPBrowser and thus Codeception.
Note
By default Wordless is configured to run acceptance (aka integration or e2e or browser) test suite alone. If you’d like to run functional or unit suites, you’ll simply have to update the yarn test
script accordingly in package.json
file.
Quick start¶
Add tests to the tests/acceptance/WPFirstCest.php
file or write your own file in the same folder.
To run acceptance test suite you have to start the test server in one terminal
yarn test:server
and in another terminal let’s actually run tests:
yarn test
While test
will simply run acceptance test suite, test:server
is a variant of the default server
task which load different Procfile
and .env
files.
Where are test configurations?¶
test/
folder. This is where your test suites lay.- PHP dependencies declared in
composer.json
file shipped within the theme. This will create a/vendor
folder inside the theme whilistyarn setup
task - custom
wp-config.php
. This will be helpful to autodymagically (automatically, dynamically, magically; just in case you were wondering 🙄) switch from development to test database whilist test suite execution - 2 test related node scripts:
yarn test:server
andyarn test
. Obviously declared insidepackage.json
- a test database on your local machine called
$THEME_NAME_test
(where$THEME_NAME
is the chosen name during Wordless’ installation process) is created whilistyarn setup
task - ad hoc
Procfile.testing
,.env.testing
and.env.ci
- ready-to-go
.gitlab-ci.yml
file into the project root
Note
vendor/
folders are ignored in .gitignore
by default
How should I write tests?¶
This documentation is not intended to giude you thourgh testing concepts nor on Codeception’s syntax. You can already find great documentation and I advice you to start from
- https://wpbrowser.wptestkit.dev/modules/wpwebdriver
- https://wpbrowser.wptestkit.dev/modules/wpbrowser
- https://wpbrowser.wptestkit.dev/modules/wpdb
where you will find Wordpress specific methods and links to base Codeception’s methods all in one place.
CI¶
We ship default configuration for GitLab by putting a .gitlab-ci.yml
file in you project’s root folder.
That is configured to run out-of-the-box. And if you use other CI’s products you can use it as a starting point for your own configuration and then delete it without any regard :)
Build and distribution¶
Since Wordless uses Webpack, we have to manage build and distribution strategies for dev and staging/production.
The source asset code is placed in
src/{javascripts|stylesheets|images}
, while built/optimized code
is placed - automatically by Webpack - in
dist/{javascripts|stylesheets|images}
See also
We offer standard approaches for both environments. They are handled -
as expected - through package.json
‘s scripts [1]:
"scripts": {
"server": "npx nf start",
"build:dev": "webpack --debug --env.NODE_ENV=development",
"build:prod": "yarn sign-release && webpack -p --bail --env.NODE_ENV=production",
"clean:js": "rimraf dist/javascripts/*",
"clean:css": "rimraf dist/stylesheets/*",
"clean:images": "rimraf dist/images/*",
"clean:dist": "yarn clean:js && yarn clean:css && yarn clean:images",
"sign-release": "git rev-parse HEAD | cut -c 1-8 > release.txt",
"lint": "yarn lint:sass",
"lint:sass": "npx stylelint 'src/stylesheets/**/*.scss'",
"test:db:create": "WP_ENV=test wp db create",
It is expected - but it’s still up to you - that before every build you will
clean the compiled files. yarn clean:dist
will do the cleanup.
Build for development¶
yarn clean:dist && yarn build:dev
Note
Most of the time you’ll be working using the built-in development server
through yarn server
, but invoking a build arbitrarily is often useful.
Build for production¶
yarn clean:dist && yarn build:prod
Production build will essentially:
- enable Webpack’s production mode
- do not produce source maps for CSS
- do minimize assets
Note
By default the production build will produce source-maps for JS; this is done to lower the debugging effort, to respect the readability of the source code in users’ browser and to simplify the shipping of source-maps to error monitoring softwares such as Sentry.
You can easily disable this behaviour setting devtool: false
in webpack.env.js
inside the prodOptions
object.
Release signature¶
You notice that build:prod
script will invoke sign-release
too.
The latter will write the SHA of the current GiT commit into the
release.txt
file in the root of the theme.
You can easily disable this behaviour if you’d like to.
release.txt
is implemented to have a reference of the code version deployed
in production and to integrate external services that should requires release
versioning (for us in Sentry).
Code linting¶
Wordless ships with preconfigured linting of SCSS using Stylelint.
It is configured in .stylelintrc.json
, you can add exclusion in
.stylelintignore
; all is really standard.
The script yarn lint
is preconfigured to run the the lint tasks.
Tip
Code linting could be chained in a build script, e.g.:
Tip
Code linting could be integrated inside a Wordmove hook
Tip
You can force linting on a pre-commit basis integrating Husky in your workflow.
PHUG optimizer¶
When performance is a must, PHUG ships a built-in Optimizer. You can read about it in the phug documentation:
The Optimizer is a tool that avoids loading the Phug engine if a file is available in the cache. On the other hand, it does not allow to change the adapter or user post-render events.
Wordless supports enabling this important optimization by setting an
environment variable (in any way your system supports it) or a global
constant to be defined in wp-config.php
. Let’s see this Wordless
internal code snippet:
if ($this->ensure_dir($tmp_dir)) {
if ( getenv('ENVIRONMENT') ) {
$env = getenv('ENVIRONMENT');
} elseif ( defined('ENVIRONMENT') ) {
$env = ENVIRONMENT;
} else {
$env = 'development';
}
if ( in_array( $env, array('staging', 'production') ) ) {
\Pug\Optimizer::call(
'displayFile', [$template_path, $locals], WordlessPugOptions::get_options()
);
} else {
$pug = new Pug(WordlessPugOptions::get_options());
$pug->displayFile($template_path, $locals);
}
where we search for ENVIRONMENT
and thus we’ll activate PHUG’s
Optimizer
if the value is either production
or staging
.
Note
Arbitrary values are not supported.
The simplest approach is to to define a constant inside wp-config.php
.
<?php
// [...]
define('ENVIRONMENT', 'production');
// [...]
Deploy¶
Wordless is agnostic about the deploy strategy. Our favourite product for deploying WordPress is Wordmove.
[1] | https://docs.npmjs.com/files/package.json#scripts |
Filters¶
The plugin exposes WordPress filters to let the developer alter specific data.
wordless_pug_configuration¶
<?php
class WordlessPugOptions {
public static function get_options() {
$wp_debug = defined('WP_DEBUG') ? WP_DEBUG : false;
return apply_filters( 'wordless_pug_configuration', [
'expressionLanguage' => 'php',
'extension' => '.pug',
'cache' => Wordless::theme_temp_path(),
'strict' => true,
'debug' => $wp_debug,
'enable_profiler' => false,
'error_reporting' => E_ERROR | E_USER_ERROR
]);
}
}
Usage example
<?php
add_filter('wordless_pug_configuration', 'custom_pug_options', 10, 1);
function custom_pug_options(array $options): array {
$options['expressionLanguage'] = 'js';
return $options;
}
wordless_acf_gutenberg_blocks_views_path¶
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | function _acf_block_render_callback( $block ) {
$slug = str_replace('acf/', '', $block['name']);
// The filter must return a string, representing a folder relative to `views/`
$blocks_folder = apply_filters('wordless_acf_gutenberg_blocks_views_path', 'blocks/');
$admin_partial_filename = Wordless::theme_views_path() . "/{$blocks_folder}/admin/_{$slug}";
if (
file_exists( "{$admin_partial_filename}.html.pug" ) ||
file_exists( "{$admin_partial_filename}.pug" ) ||
file_exists( "{$admin_partial_filename}.html.php" ) ||
file_exists( "{$admin_partial_filename}.php" )
) {
$admin_partial = "{$blocks_folder}/admin/{$slug}";
} else {
$admin_partial = "{$blocks_folder}/{$slug}";
}
|
Usage example
<?php
add_filter('wordless_acf_gutenberg_blocks_views_path', 'custom_blocks_path', 10, 1);
function custom_blocks_path(string $path): string {
return 'custom_path';
}
This way Wordless will search for blocks’ partials in
views/custom_path/block_name.html.pug
so you can use render_partial('custom_path/block_name')
to render them in your
template.
The default path is blocks/
.
Note
The path will be always relative to views/
folder
CLI¶
When a Wordless theme is activated and you are inside project’s path, you automatically get an ad-hoc WP-CLI plugin.
Typing wp help
you’ll notice a wordless
subcommand.
All subcommands are self-documented, so you can simply use, e.g.:
wp help wordless theme upgrade
to get the documentation.
Development stack¶
Here are the stack components of Wordless’ development workflow:
- WordPress plugin
- A theme with a convenient default scaffold
- Webpack
- WP-CLI
Contents
Nodejs¶
Nodejs is used for all the front-end build chain.
You need to have Node installed on your machine. The setup is not covered by this documentation.
Version¶
Each release of Wordless is bound to a node version. It is declared
inside package.json
.
Wordless is tested with the enforced nodejs version and the shipped yarn.lock
file. You’re free to change version as you wish, but you’ll
be on your own managing all the dependancies.
Development environment¶
Starting by saying that with a
yarn run server
you should be up and running, let’s see in depth what happens behind the scenes.
YARN¶
yarn run
(or simply yarn scriptName
) will search for a scripts
section inside your package.json
file and will execute the matched script.
"scripts": {
"server": "npx nf start",
"build:dev": "webpack --debug --env.NODE_ENV=development",
"build:prod": "yarn sign-release && webpack -p --bail --env.NODE_ENV=production",
"clean:js": "rimraf dist/javascripts/*",
"clean:css": "rimraf dist/stylesheets/*",
"clean:images": "rimraf dist/images/*",
"clean:dist": "yarn clean:js && yarn clean:css && yarn clean:images",
yarn server
will run nf start
, where nf
is the Node Foreman
executable.
Foreman¶
Node Foreman (nf
) could do complex things, but Wordless uses it only
to be able to launch multiple processes when server
is fired.
wp: wp server --host=0.0.0.0
webpack: npx webpack --debug --watch --progress --color --env.NODE_ENV=development
mailhog: mailhog
As you can see, each line has a simple named command. Each command will be launched and foreman will:
- run all the listed processes
- collect all STDOUTs from processes and print theme as one - with fancyness
- when stopped (CTRL-C) it will stop all of the processes
wp server¶
Launched by nf
. Is a default WP-CLI command.
We are invoking it within a theme directory, but it will climb up directories
until it finds a wp-config.php
file, then it will start a PHP server
on its default port (8080) and on the 127.0.0.1
address as per our config.
Note
You can directly reach http://127.0.0.1:8080
in you browser in order
to reach wordpress, bypassing all the webpack things we’re going to show
below.
BrowserSync¶
The only relevant Webpack part in this section is BrowserSync. It will
start a web server at address 127.0.0.1
on port 3000.
This is where your browser will automatically go once launched.
new BrowserSyncPlugin({
host: "127.0.0.1",
port: 3000,
proxy: {
target: "http://127.0.0.1:8080"
},
watchOptions: {
ignoreInitial: true
},
files: [
'./views/**/*.pug',
'./views/**/*.php',
'./helpers/**/*.php'
]
}),
As you can see from the configuration, web requests will be proxy-ed to the
underlying wp server
.
Since BrowserSync is invoked through a Webpack plugin (browser-sync-webpack-plugin) we will benefit from automatic browser autoreloading when assets are recompiled by Webpack itself.
The files
option is there because .pug
files are not compiled by
webpack, so we force watching those files too, thus calling autoreload on
template changes too.
See also
Code compilation for other Webpack default configurations
Note
BrowserSync’s UI will be reachable at http://127.0.0.1:3001
as per
default configuration.
Warning
If you will develop with the WordPress backend in a tab, BrowserSync will ignorantly reload that tab as well (all tabs opened on port 3000 actually). This could slow down your server. We advise to use the WordPress backend using port 8080 and thus bypassing BrowserSync.
MailHog¶
MailHog is an email testing tool for developers:
- Configure your application to use MailHog for SMTP delivery
- View messages in the web UI, or retrieve them with the JSON API
- Optionally release messages to real SMTP servers for delivery
Wordless is configured to use it by default, so you can test mailouts from your site, from WordPress and from your forms.
The UI will be at http://localhost:8025 as per default configuration.
When you spawn yarn server
, you’ll have an environment variable
exported thanks to the .env
file:
MAILHOG=true
This will trigger the smtp.php
initializer:
<?php
add_action( 'phpmailer_init', 'wl_phpmailer_init' );
function wl_phpmailer_init( PHPMailer $phpmailer ) {
$mailhog = getenv('MAILHOG');
if ($mailhog !== "true")
return false;
$phpmailer->IsSMTP();
$phpmailer->Host = 'localhost';
$phpmailer->Port = 1025;
// $phpmailer->SMTPAuth = true;
// $phpmailer->Username = 'user';
// $phpmailer->Password = 'password';
// $phpmailer->SMTPSecure = 'ssl'; // enable if required, 'tls' is another possible value
}
Debug in VSCode¶
We ship a .vscode/launch.json
in theme’s root which is preconfigured to
launch debugger for XDebug and for JS (both Chrome and FireFox). In order to
use these configuration you’ll need to install some plugins in the editor:
Note
You may need to move .vscode/launch.json
in another location if you
are not opening the theme’s folder as workspace in VSCode (maybe you prefere to
open all the WordPress installation? Don’t know…). It’s up to you to use it
as you need it.
Code compilation¶
First things first: using “alternative” languages is not a constraint. Wordless’s scaffolded theme uses the following languages by default:
- PHUG for views as an alternative to PHP+HTML
- ES2015 transpiled to JS using Babel
- SCSS for CSS
You could decide to use plain languages, just by renaming (and rewriting) your files.
Wordless functions which require filenames as arguments, such as
<?php
render_partial("posts/post")
// or
javascript_url("application")
will always require extension-less names and they will find your files whatever extension they have.
See also
PHUG paragraph @ Using plain PHP templates
Anyway we think that the default languages are powerful, more productive, more pleasant to read and to write.
Add the fact that wordless will take care of all compilation tasks, giving you focus on writing: we think this is a win-win scenario.
PHUG¶
Pug is a robust, elegant, feature-rich template engine for Node.js. Here we use a terrific PHP port of the language: Phug. You can find huge documentation on the official site https://www.phug-lang.com/, where you can also find a neat live playground (click on the “Try Phug” menu item).
It comes from the JS world, so most front-end programmers should be familiar with it, but it is also very similar to other template languages such as SLIM and HAML (old!)
We love it because it is concise, clear, tidy and clean.
h2 Post Details
- the_post()
.post
header
h3!= link_to(get_the_title(), get_permalink())
content!= get_the_content()
Certainly, becoming fluent in PUG usage could have a not-so-flat learning curve, but starting from the basics shuold be affordable and the reward is high.
Who compiles PUG?¶
When a .html.pug
template is loaded, the wordless plugin will automatically
compile (and cache) it. As far as you have the plugin activated you are ok.
Important
By default, you have nothing to do to deploy in production, but if performance is crucial in your project, then you can optimize. See PHUG optimizer for more informations.
JS and SCSS¶
Here we are in the Webpack domain; from the compilation point of view there is nothing Wordless-specific but the file path configuration.
Configuration is pretty standard, so it’s up to you to read Webpack’s
documentation. Let’s see how paths are configured in webpack.config.js
.
Paths¶
Paths are based on the Wordless scaffold. Variables are defined at the top:
2 3 4 5 | const srcDir = path.resolve(__dirname, 'src');
const dstDir = path.resolve(__dirname, 'dist');
const javascriptsDstPath = path.join(dstDir, '/javascripts');
const _stylesheetsDstPath = path.join(dstDir, '/stylesheets');
|
and are used by the entry
and output
configurations:
18 19 20 21 22 23 24 25 26 | entry: entries.reduce((object, current) => {
object[current] = path.join(srcDir, `${current}.js`);
return object;
}, {}),
output: {
filename: "[name].js",
path: javascriptsDstPath
},
|
CSS will be extracted from the bundle by the standard mini-css-extract-plugin
129 130 131 | cacheGroups: {
commons: {
name: 'commons',
|
Inclusion of compiled files¶
Wrapping up: the resulting files will be
dist/javascripts/application.js
dist/stylesheets/screen.css
As far as those files remain as-is, the theme will automatically load them.
If you want to edit names, you have to edit the WordPress asset enqueue configurations:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <?php
// This function include main.css in wp_head() function
function enqueue_stylesheets() {
wp_register_style("main", stylesheet_url("main"), [], false, 'all');
wp_enqueue_style("main");
}
add_action('wp_enqueue_scripts', 'enqueue_stylesheets');
// This function include jquery and main.js in wp_footer() function
function enqueue_javascripts() {
wp_enqueue_script("jquery");
wp_register_script("main", javascript_url("main"), [], false, true);
wp_enqueue_script("main");
}
add_action('wp_enqueue_scripts', 'enqueue_javascripts');
|
Note
The stylesheet_url
and javascript_url
Wordless’ helpers
will search for a file named as per the passed parameter inside the default
paths, so if you use default paths and custom file naming, you’ll be ok, but
if you change the path you’ll have to supply it using other WordPress
functions.
Multiple “entries”¶
“Entries” in the WebPack world means JS files (please, let me say that!).
Wordless is configured to produce a new bundle for each entry and by default
the only entry is main
require('./javascripts/application.js');
require('./stylesheets/screen.scss');
As we’ve already said having an entry which requires both JS and SCSS, will produce 2 separate files with the same name and different extension.
Add another entry and producing new bundles is as easy as
- create a new file
- write something in it, should it be a
require
for a SCSS file or a piece of JS logic - add the entry to webpack config
const entries = ['main', 'backend']
include somewhere in your theme. For example in the WP’s asset queue in
default_hooks.php
function enqueue_stylesheets() { wp_register_style("main", stylesheet_url("main"), [], false, 'all'); wp_register_style("backend", stylesheet_url("backend"), [], false, 'all'); wp_enqueue_style("main"); wp_enqueue_style("backend"); } function enqueue_javascripts() { wp_enqueue_script("jquery"); wp_register_script("main", javascript_url("main"), [], false, true); wp_register_script("backend", javascript_url("backend"), [], false, true); wp_enqueue_script("main"); wp_enqueue_script("backend"); }
or add it anywhere in your templates:
header = stylesheet_link_tag('backend') footer = javascript_include_tag('backend')
Browserslist¶
At theme’s root you’ll find the .browserlistsrc file.
By default it’s used by Babel and Core-js3 to understand how to polifill your ES2015 code. You can understand more about our default configuration reading Babel docs at https://babeljs.io/docs/en/babel-preset-env#browserslist-integration
Stylelint¶
We use Stylelint to lint SCSS and to enforce some practices. Nothing goes out of a standard setup. By the way some spotlights:
- configuration is in
.stylelintrc.json
file - you have a blank
.stylelintignore
file if you may need yarn lint
will launch the lint process- if you use VS Code to write, we ship
.vscode/settings.json
in theme’s root, which disables the built-in linters as per stylelint plugin instructions. You may need to move those configurations based on the folder from which you start the editor.
Using plain PHP templates¶
Let’s take the unaltered default theme as an example. In views/layouts
we
have the default
template which calls a render_partial
for the
_header
partial.
doctype html
html
head= render_partial("layouts/head")
body
.page-wrapper
header.site-header= render_partial("layouts/header")
section.site-content= wl_yield()
footer.site-footer= render_partial("layouts/footer")
// jQuery and application.js is loaded by default with wp_footer() function. See config/initializers/default_hooks.php for details
- wp_footer()
h1!= link_to(get_bloginfo('name'), get_bloginfo('url'))
h2= get_bloginfo('description')
Let’s suppose we need to change _header
in a PHP template because we don’t
like PUG or we need to write complex code there.
Warning
If you have to write complex code in a view you are on the wrong path :)
Rename
_header.html.pug
in_header.html.php
Update its content, e.g.:
views/layouts/_header.html.php¶<h1> <?php echo link_to(get_bloginfo('name'), get_bloginfo('url')); ?> </h1> <h2> <?php echo htmlentities(get_bloginfo('description')) ?> </h2>
Done
When render_partial("layouts/header")
doesn’t find _header.html.pug
it
will automatically search for _header.html.php
and will use it as is,
without passing through any compilation process.
Conclusions¶
As you can see, Wordless does not force you that much. Moreover, you will continue to have its goodies/helpers to break down views in little partials, simplifying code readability and organization.