Posted by & filed under Personal.

WordPress is the worlds most popular installable blogging / CMS platform, running on the worlds most commonly used web language PHP, and can be installed and configured on the worlds most popular shared hosting stack, LAMP. Chances are you’ve already been to half a dozen websites built with WordPress today. If you’re a regular reader of my blog, you probably already have a WordPress site or two.

I’m willing to bet that if you’re developing themes or plugins for WordPress, you hate it, and if you’re just there to write content, you love it. WordPress does have a great administrative interface after all.

I suppose any popular software is going to have a few haters. If you know me, you know that I’m a big fan of starting from scratch every now and then, and I’d like to explain why I feel this would be a great opportunity for WordPress 4.x.

Syntax

If you are a web designer, you might not think the code is that bad. You might consider yourself more of an HTML/CSS web designer than a programmer, and that know how to bend WordPress to your will. If you are a web developer, writing PHP for a living, you know that the code is very bad.

All of these issues comes from PHP being embedded in HTML documents. In the bigger frameworks this is discouraged, and all PHP documents should have a single opening tag at the top (and no closing tags). Some frameworks which allow PHP templates (e.g. Kohana, CodeIgniter), use the single PHP tag approach for all files except for views, where it is recommended only the simplest of PHP be used (echo variables, looping).

Here’s a quick comparison of some normal PHP code, and the format commonly used by WordPress.

Common WordPress PHP Theme Code:

This is called the Alternative Syntax, and is used for control structures. I’ve only ever seen it used in presentation related code. Most developers shun it, and I don’t think anyone is crazy enough to use it in logic areas of their application.

<?php if ( get_option('comment_registration') && !is_user_logged_in() ) : ?>
<div class="alert help">
  <p><?php printf( __('You must be %1$slogged in%2$s to post a comment.'), '<a href="<?php echo wp_login_url( get_permalink() ); ?>">', '</a>' ); ?></p>
</div>
<?php else : ?>
  <p>comment code</p>
<?php endif; ?>

“Better” WordPress Theme Code:

Here, control statements use curly brackets to designates blocks of code. The whitespace is a little better, but since we’re mixing HTML and PHP there’s no perfect solution (indented PHP/HTML source will mean improperly indented rendered HTML0. I also took some of the function calls out of longer lines and assigned them to variables, something PHP developers often do, but theme designers often don’t. But, it still looks horrible! What the hell does __() mean, anyway?

<?php
$can_comment = get_option('comment_registration');
$logged_in = is_user_logged_in();

if ( $can_comment && !$logged_in ) {
  $login_url = wp_login_url( get_permalink() );
  $login_message = 'You must be %1$slogged in%2$s to post a comment.';
  ?>
  <div class="alert help">
    <p><?php printf( __($login_message), "<a href='$login_url'>", '</a>' ); ?></p>
  </div>
  <?php
} else {
  ?>
    <p>comment code</p>
  <?php
}
?>

At this point you might be thinking, “developers can pick the cleaner method for writing PHP code, but they just don’t, shame on them”. The default WordPress themes actually promote the alternative syntax, which trickles down to theme developers. However that isn’t the point; theme developers should not be writing any PHP code. Themes are meant to simply build an HTML document, not be a place for running ad hoc code.

Arguments against PHP for Presentation

The big argument for not allowing logic in presentational code is called Separation of Concerns, which means you want to keep your code segregated into different areas based on what the code does. A common approach for doing this is the Model View Controller (MVC) pattern, where Models represent database calls or business logic, Views represent the presentation related code, and Controllers tie everything together and direct requests. Themes kind of represent Views, however their ability to intermingle database calls and logic makes this questionable.

Another argument for not allowing logic in themes is that rogue developers are no longer able to put nasty code in their themes. Go ahead and read your WordPress spam log. How many of those posts originate from hacked WordPress themes hosted on other peoples websites (e.g. the URLs contain /wp-content/themes/ or /wp-content/uploads/)? By using a strict templating language, this is more difficult.

Also, PHP is a lot more complex than alternatives, and theme developers need to learn it, even if they never intend on doing server-side programming.

Arguments for PHP for Presentation

The argument against a templating language is that the theme developer gets a lot of control over site appearance with the ability to add PHP everywhere. Without raw PHP, the amount of unique themes that can be created is reduced.

Another argument is that PHP itself is a templating language, since it allows PHP code to intermingle HTML documents, why not just use that? While this is true, the amount of control that PHP offers is just too much, a tiny subset is needed for proper theme development.

Rendering of templating languages can take time, and therefor will make the site slower. While this is true, the renderer can convert the theme into a PHP script and cache it to disk, so that this slowdown only occurs once.

Templating Language

My proposed solution for WordPress to get their themes better under control is to adopt a templating language, and require themes to use them. A popular theme engine is Mustache, which uses curly braces to denote variables and control structures, and has a very small subset of logic and code execution ability (as compared to PHP as a whole). If you’ve ever edited a Tumblr theme, you’ve seen a similar syntax.

Sample Mustache Syntax:

Control structures are designated with different symbols, not particularly easy to understand at first glance. This is a pretty popular, platform-agnostic templating language.

Hello {{name}}
You have just won ${{value}}!
{{#in_ca}}
Well, ${{taxed_value}}, after taxes.
{{/in_ca}}

Sample Tumblr Syntax:

Tumblr is a bit simpler, branching and looping control structures have been combined into a simpler ‘block’ statement.

{block:Text}
    <li class="post text">
        {block:Title}
            <h3><a href="{Permalink}">{Title}</a></h3>
        {/block:Title}
        {Body}
    </li>
{/block:Text}

Existing Themes

The biggest asset of WordPress is the large number of themes and plugins available for it. Of course, by switching to a templating language such as Mustache, the existing repository of PHP based themes are no longer valid. To take care of this, Automattic (the company behind WordPress) could bundle a plugin with WordPress 4.x that allows loading of old templates, which would be disabled by default. Keeping that code out of core would help keep the overall project more manageable and secure.

Helpers

By switching to a templating language, themes do lose the ability to throw ad-hoc PHP everywhere, which is required by many themes. That is what Helpers are for. Helpers are pieces of code that are called by View files. WordPress could keep the functions.php concept, but the code inside of it would be more structured, and would offer a nice class-based API. Instead of allowing the declaration of global functions, it would require code to use a class and extend the templating engine syntax.

Of course, theme developers can still put naughty code in this functions file. For this reason, the WordPress theme website should put disclaimers on themes which make use of this file, even make them slightly harder to discover (e.g. disabled from search results by default), encouraging developers to not use them. Applications that are sandboxed, like apps in the OS X store and even Facebook apps, have a way of granting permissions to use certain functionality, unfortunately PHP doesn’t have support for this.

There should also be a voting system, where theme developers can pick which functions they want to be available in WordPress core, which should reduce dependency on a functions file over time. Automattic could even keep an eye on functions.php files of various themes to determine what these are. I’m not sure if this currently happens, but the functions.php files should be parsed for obvious bad code, such as eval(), system(), maybe even base64_decode().

Conclusion

These are my ideas to make the world of WordPress template development a better place. We’d clean up the syntax on WordPress themes, enforce Separation of Concerns, reduce the number of malicious WordPress themes, designers wouldn’t need to learn a programming language, and PHP developers would enjoy working with themes more.

Mustache and Tumblr are just two templating languages, there are dozens if not hundreds of them. Which would you recommend?

11 Responses to “What WordPress 4.x Could Be”

  1. Matt

    I think that might be ok so long as all the PHP functions are in place for those who don’t wish to use the template syntax. Template languages are better maybe for people unfamiliar with PHP. In all honesty though WordPress is so easy to program for, which is what most developers love about it.

    I used expression engine for a few years and they use a template language similar to Mustache syntax. It’s all well and good until you need to do something that requires real programming. The template language and standard PHP don’t play nice together. They are parsed at different times often resulting in crazy code work arounds that just make you feel like it’s duct taped together.

    Reply
  2. Jacob Santos

    This argument again. Sigh.

    Perhaps a bit of research would have led you to the articles about PHP already being a templating language and therefore creating an templating language in a templating language is nonsense.

    The second point and this one is important, is that you don’t actually solve any problem and actually create a whole lot of issues from your proposed solution. The problem being that you have to have some way to execute functions in the code.

    Your point seems to be more that more logic should be moved to models and libraries than be contained in the views that WordPress has.

    Reply
  3. Romulo De Lazzari

    I’m working on a theme using Mustache, and I’m really happy with this aproach. The big issue with WP and MVC are the “talkative functions”, such as body_class(), wp_head(), contact_form() and several others.

    For these functions, I had to use this “dirty hack”:


    // shut up WP
    function function_wrapper($func, $args = null)
    {
    ob_start();
    call_user_func($func, $args);
    return ob_get_clean();
    }

    Reply
  4. Chris Olbekson

    What’s wrong with using the alternate syntax? In some cases like in a theme I think it actually helps organize the code.

    I also disagree with your point on assigning everything to variables. I used to do that when I first started with programming and WordPress and evolved since then. In some cases it is better but for most part it just takes makes code longer and takes up space and memory.

    Here is even MUCH BETTER THEME CODE than the two examples you posted:

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>