JavaScript, learn to use JavaScript, using JavaScript in WordPress, learn to code in WordPress, WordPress coding tips, WordPress coding tutorials, how to use wp.template, using wp.template, wp.template tutorial

How to Use wp.template, WordPress’ Underscore.js Template Method

Like many developer agencies, we have a few different audiences, including clients (current and prospective) and other developers. Our aim is to serve all of our audiences, who fall on a broad spectrum of technical knowledge. Even if you’re not a professional developer, we know that many of you still educate yourselves on the technology used on your site–and we want to help! If there’s anything we cover that you don’t understand (or anything you’d like to see us cover that’s WordPress related, even 101!), please let us know. There are no stupid questions.

That said, let’s dive into something fun: WordPress’ Underscore.js Template Method, wp.template.

If you’re not yet familiar, wp.template() is a cool little JavaScript utility method that is provided with the WordPress core ‘wp-util’ script. At its core, it uses the Underscorejs .template() method.

WordPress uses this utility to load templates for all of the backbone views, but backbone is not required to use it. First, I’ll demonstrate using wp.template() with a little jQuery in order to output some JavaScript data into an HTML template, then later as a bonus, we’ll rebuild wp.template() as our own module with some additional features.

Keep in mind: this is meant to be an example presented as simply as possible, and not something you would copy/paste into production code. Please continue to follow standard best practices, including things like putting JavaScript in its own file, avoiding anonymous functions, internationalizing your text strings, etc.

By default, the method requires a script tag with an id of tmpl-my-template-name. Because all of WordPress uses this templating method/system, you will want to make sure you properly prefix your ids, so as not to conflict with another template that may be loaded on the page. That script tag should also have a type of “text/template.”1

Let’s get started:

function zao_item_status_tmpl() {
    <script type="text/template" id="tmpl-zao-item-status">
        <span class="zao-status" data-id="{{ }}">
        <# if ( ) { #>
            <div class="zao-item-status">
                <span class="zao-status-color" style="display: inline-block;background-color:{{ data.status.color }};width:10px; height:10px;"></span>
                {{{ }}}
                    {{ }}
                {{{ data.close }}}
        <# } else { #>
        <# } #>

So now we have the proper script template tag ready to go in a PHP function, with unique id, tmpl-zao-item-status. As you can see, this isn’t 100% standard HTML. You can see we are using Mustache-inspired data variables, as well as Underscorejs logic blocks.

From the Codex:

WordPress defines its own interpolation tags using the _.template( options ) to avoid incompatibility in some PHP configurations with asp_tags enabled. The WordPress-specific interpolation syntax is inspired by Mustache templating syntax:

  • Interpolate (unescaped): {{{ }}}
  • Interpolate (escaped): {{ }}
  • Evaluate: <# #>

An important bit to understand is the <# and #>, which signals the opening/closing of raw JavaScript output, so you can do things like logic operators (like the if statement in the example above). You can also see we’re taking advantage of the unescaped interpolation when we output the and data.close parameters, since those will contain HTML and we don’t want that escaped.

At this point, let’s hook into WordPress so we can see this in action.

Add this snippet somewhere in your theme’s functions.php file, or a custom plugin:

// Output this at the top of the post-edit screen just below the title input.
add_action( 'edit_form_after_title', function() {
    <span class="zao-status"><span style="display: inline-block;background-color:red;width:10px; height:10px;"></span> Please wait...</span>
} );

If you go to a new-post or post-edit screen, you should see something like this:

That doesn’t do much for us. We’re going to need some JavaScript setup to grab our updated status and update the status markup. To simplify, we’ll simply fake an AJAX request by setting a short delay. You could also using something like the Zao Mock API to mock some API requests/responses.

The JavaScript:

function zao_item_status_js() {
    <script type="text/javascript">
        // Wait for the dom to be ready..
        jQuery( function( $ ) {

            // Get the template function corresponding to our template markup.
            var template = wp.template( 'zao-item-status' ); // uses script tag ID minus "tmpl-"

            // Let's wait a tick, so we can see it go from yellow to green.
            setTimeout( function() {

                // Let's fake some data (maybe this is data from an API request?)
                var tmplData = {
                    id: 1,
                    status: {
                        name: 'Success!',
                        color: 'green'
                    open: '<span class="status-name" style="color:green">',
                    close: '</span>'

                // Send the data to our new template function, get the HTML markup back.
                var html = template( tmplData );

                // Now let's replace the contents of the existing markup with our updated template markup.
                $( '.zao-status' ).html( html );
            }, 1000 );

The code comments should be self-explanatory, but to recap:

  1. Call wp.template() with the ID of the script tag we created earlier minus the tmpl- prefix
  2. Fake an API request by setting a one second delay
  3. Generate an object of data and pass it to our new template function which returns the compiled HTML
  4. Take that HTML and replace the existing.

We now have the JavaScript output in a PHP function, which we can hook into the footer. We have almost all the pieces we need to make this work, so let’s update our edit_form_after_title anonymous function:

// Output this at the top of the post-edit screen just below the title input.
add_action( 'edit_form_after_title', function() {

    // Hook in our template script tag to the footer.
    add_action( 'admin_footer', 'zao_item_status_tmpl' );

    // Hook in our custom JS for updating the status.
    add_action( 'admin_footer', 'zao_item_status_js' );

    // Now, enqueue the WP util script so we can use wp.template
    wp_enqueue_script( 'wp-util' );

    // Make the initial output have a yellow status square
    <span class="zao-status"><span style="display: inline-block;background-color:#ffe24d;width:10px; height:10px;"></span> Please wait...</span>
} );

With that, we should see the status go from yellow (“Please wait…”) to green (“Success!”).

wp.template success! gif

wp.template success!

Hopefully, this basic example will help you get started using wp.template() in your own work, but if you have any questions, please leave comments below.

The full output for this example snippet can be found here.

If you’re still with me: now that we’ve covered the basics of the WordPress’ utility, you might be interested in a similar utility based on wp.template() which I created, _templatize. This script simplifies the above steps a little by combining the template-getting and data-sending, and also provides a feature that allows creating a template by passing it an HTML string (vs being tied to a tmpl- script tag in the dom). As a bonus, you can see the above snippet updated to use _templatize here.

  1. The key is that it shouldn’t be type="text/javascript" (or no type specified). More info 
Zao, learning to code, WordPress developers, WordPress ecommerce, learn to build WordPress, learning to build in WordPress, learning WordPress, how to use WordPress

Five Things I Wish Someone Told Me When I Learned to Code

I haven’t been in the software development industry for loads of time, but thanks to some amazing people who championed my growth, I slingshotted in quicker than some other peers who did it all on their own. (Props to you individuals, by the way, that wrestled it all out by yourself–you are unstoppable!)

After thinking a bit about my experience I came up with five things I wish I had known when I started developing:

1. It’s 100% normal to feel like you’re drowning

I stumbled my way into coding; it initially started as a hobby.

At first, everything was bite-sized and easy. I was blissfully unaware of how little I knew. Once that bubble popped, my lack of knowledge was overwhelming. Everywhere I turned there was something I could not do.

I remember the first time I tried poking around in the Codex. I ran away thirty seconds later because it all seemed like Greek! I literally did not have the capacity or supporting framework to “get it.” I wish I had known in advance how often it would feel like drowning and that it was fine.

2. Just Keep Learning, Just Keep Learning

Go after all the low hanging fruit that you can. It might seem like a waste of time to spread yourself so wide, but if you are truly a newbie and have no context for the developing world, the wider you go, the wider your foundation will be. Although you won’t be fully aware of it at the time, you’ll fill in the gaps of your understanding so you can level up.

When I felt like I was drowning, I continued to chip away at the pieces I could master and walked away from the pieces that made no sense to me. It paid off in the long run.

You can only handle so much drowning before you give up. By moving on, I kept my overload threshold in the green and experienced small wins that boosted my confidence.

Every so often, I would return to the Codex and give it a go again. When it still wasn’t useful for me, I moved on. I remember the day I was working on something, jumped around several Codex pages…and realized it made sense to me. Suddenly, the Codex was in my toolbox. By expanding my understanding in other areas, I built a framework that allowed me to tackle the previously impassable problems.

I wish I had given myself the permission earlier on to move on when it suited me. While there is a satisfaction to mastering something, I have found the field to be so wide, deep, and complex that it is rare to master something the first go around. Spending all your resources to come out utterly defeated is more costly than saying, “I don’t get it, so I’m going to move on to something else and return to it another time.”

It changed my experience from perpetually drowning to recognizing that I need to play in the wading pool a bit longer.

Note: This should go without saying, but don’t put yourself in a situation where you have committed to do something that is beyond your abilities for a client…because then, you don’t have the permission to walk away from it.

3. Hone in on your trusted sources

The internet is amazing and Google a robust resource, but not all of the resources out there are reliable.

As helpful as Stack Overflow is, quality control is not always a guarantee. Many of the solutions provided are hacks, instead of the industry standard approach to the problem. When you’re starting out, it’s hard to know who you should and shouldn’t listen to. It’s imperative to find good sources that you can soak up. This might require reaching out to experts in the business and find out who they trust.

My introduction to coding started with a free online coding tutorial resource. It was great for the most basic things. However, the further I got down the rabbit hole, I discovered that some of what they were teaching was completely wrong. Fortunately, friends who are professional developers pointed me to some credible resources.

It is hard to unlearn something foundational if you learned it wrong the first time. You only have so much time and you can spend eternity reading about all the different approaches.  Find approaches you can build on so it’s not considered time wasted later.

Team Treehouse proved to be an invaluable resource for me. They are trustworthy and they are actually good at teaching–a huge bonus because not all developers are good at breaking down what is natural for them into bite sized pieces for newbies.

4. After you learn it, build it

I cannot tell you how often I’d go through a tutorial and think to myself, “This makes complete sense. I get it!”

I followed with the tutorial and find myself at the end with the desired product. Ta-da! I learned it, right?

More times then I can count, I noticed that stepping away for the weekend would be enough for me to completely forget it. I found that after completing a tutorial, it was really helpful to go through and build the entire project again without the tutorial.

That was the real test of what I had actually learned, versus what I was regurgitating. It is great to follow along with a tutorial, but that’s only the first level. You need to practice it several times before you get it. The more you build it, the more muscle memory you create.

I wish I rebuilt the same things over and over instead of moving on to the next skill before mastering what I initially focused on.

One final point on building: going through other people’s tutorials is a great way to gain knowledge. However, reproducing something that already exists does not activate your creative thinking.

I discovered if I tried to implement a skill in a different context than the tutorial, I understood the steps to build one specific solution, but didn’t always grasp the concept in its entirety and how it could be applied to different situations. After you master a project on your own without the tutorial, try it again but with a different outcome as the goal. This will keep the skill pliable for you.

5. Get excited about pet projects

One of my biggest struggles when learning to code was that I had no idea what to build on my own. I desperately wanted to practice and try things out, but I had zero idea where to start.

As I mentioned earlier, you can only drown for so long before you give up. The antidote to this is passion. If you are really passionate about what you are building, you will have more endurance to push forward when the going gets tough.

Additionally, the great things about pet projects is that they are often side projects. You probably have other pressing matters that need attending, and so your project will get put on the back burner. This is fantastic!

When you return to it you will see your work through the eyes of a new developer. You will learn first hand the importance of commenting because you’ll probably have forgotten about why you did some of what you did and what all the moving pieces do.

As you improve your skills, you’ll find that when you return to your old work, you’ll be embarrassed by some of your approaches. The upside: you’ll have an opportunity to practice refactoring. These skills are super important and less painful to learn on your own project then in a group project where you’re impacting your peers and clients.

I wish I had known all of this sooner.  What about you? What things do you wish your baby developer self knew?

what developers need to know, developer education, code audits 101, how to do a code audit, what should i offer in a code audit, what is a code audit, how to price a code audit, code audit tools, code audit analysis, code audit deliverable, code audit checklist, software code audit

What Developers Need to Know Before Offering Code Audits

So, you’re a developer. You’ve thought about offering code audits, but maybe you haven’t had a clear idea of what your code audit should provide, why clients go seeking one, or how to price the service.

In January, we covered the questions clients need to ask their developer before getting a code audit, and offered some guidance on how to vet their vendor. This time around, we’re going to cover the developer side of things: why clients seek code audits, what questions you need to be asking before you get started, and how code audits lay a good foundation for a future relationship with your clients.

Why Clients Look For Code Audits

Yes, of course, there’s a ton of information available on the internet, including all the information that a client could need regarding the basics of site performance and functionality. Most clients, however, either don’t have the time to do this research, or don’t have the technical expertise to make sense of it all.

Code audits benefit clients by empowering them to make informed choices about the future of their technology.

When clients are coming to you asking about code audits and an assessment of their technology, they’re looking for your extensive knowledge that empowers you to look at their code, quickly parse the information, and dictate which things are worth building on.

Basic Code Audit Questions

There are a few standard questions every developer should ask before diving right into someone’s code.

What type of project are we auditing?

Knowing what kind of project your client is looking to have assessed is vital to understanding how much time it will take you–and whether or not you’re a good fit for the project. Is it a website audit or a full-scale plugin? An eCommerce site or an app? Knowing what you’re looking at upfront helps you figure out if you have the right expertise to do your client justice…and what kind of scope you’ll set out for your clients.

Are we auditing code that has been custom written by a previous developer or is this a distributed plugin that we’re assessing?

Knowing the origins of the code can help you set your expectations. Custom code created by another developer may take longer to dissect, especially if something is buggy. Is the developer someone you know? If so, that gives you informative context on what you’re dealing with–and provides a point of contact for figuring things out. If not, you know that it may take you longer to dig through and assess what is happening with the code at hand.

If it’s a plugin downloaded from the WordPress Plugin Repository, you know that checking on when it was last updated, as well as going to the plugin page to look over developer updates and reviews, will be a part of your process.

The Most Crucial Thing Developers Need to Understand

The key to delivering a valuable code audit is understanding your client’s underlying goals. If you’re lucky, your client understands their own business goals, and has mapped out the future of their business, too. That information is an enormous assist in guiding you through this process.

The scope of a code audit can vary wildly depending on a client’s objectives.

Here are just a few reasons our clients have sought out code audits:

They want to get rid of a tool, but need a good reason.

Sometimes, a client doesn’t like a tool, but they don’t have the technical knowledge to evaluate whether or not it’s a necessity. They need someone to assess if this tool is truly their best option–or even something they need at all.

There’s a plugin that is freely available, but they want to make sure it’s contributing to a solid technical foundation for their business.

Our websites are our online real estate. A shop owner wouldn’t want to open up their store in a crumbling building, and business owners don’t want to open up their shop on a lousy website. They’re coming to you to find out whether these distributed plugins are their best choices and will set them up for future success.

Their site is custom built, but it’s slow, and they suspect the custom build may be the culprit.

This is fantastic information, because it tells you, the developer, that they’re looking for a performance based evaluation. Now, you know you need to find out more information about their business before getting started. Maybe their business has outgrown their site; the code they had built was once working, but now, it can’t scale. This gives you an opportunity to evaluate performance in a specific, measured way, and give recommendations accordingly.

Their business has changed, but their technology hasn’t.

For example, some plugins do well if they’re on a site that has no users logged in. However, if that same site has switched to a subscription model, it won’t have caching layers that allow the plugins to run as smoothly. Your client may not know this difference. All they know is that they made the switch when they needed to shift their business model. They didn’t recognize the impact it would have on their technology.

Understanding the history of your client’s business (and the trajectory of where they intend to go) provides context regarding what needs to be assessed and what kind of upgrades would serve them best.

There are two plugins that do the same thing, but which one is best for their site?

Once again, this comparison that may be available out there on the internet, but they want your expert insight. If you’ve assessed your client’s business goals and trajectory, you can make a recommendation based on their specific business model. That’s a boon for both you and them! It means that you have something to offer that they can’t get anywhere else.

What About Pricing?

One of the toughest quandaries of them all! Code audit pricing can differ wildly depending on the client. We’ve quoted simple code audits at anywhere from $2,500-$5,000, and have quoted much more complex audits of entire platforms/systems for $50,000+.

Why the disparity?

Three crucial factors come into play:

The deliverable

As we’ve said before, we offer a comprehensive deliverable, filled with detailed information. We take a pragmatic approach, and provide a transparent, realistic look at associated costs with the recommendations we make.

Your clients will need to know what they can expect from you. Is it a document or a confirmation email? Is it a walkthrough on a call? The details of the deliverable determine how much time it will take to create and what value you’re providing.

The scope of the audit

If you’re already a working developer, I don’t have to tell you how scope impacts cost. When pricing services, you need to know what kind of assessment is needed and how much time it will take.

The amount of experience you have

Although we’d all like to dive in and make a bazillion dollars at the start, less experience usually dictates a lower rate. Do the research on what other developers in the same experience bracket are charging. Evaluate what your time is worth (and don’t fall prey to Imposter Syndrome!). Realistically assess how your experience (or lack thereof) informs your expertise and turnaround.

Code Audits: Good for Your Clients and You

Code audits benefit clients by empowering them to make informed choices about the future of their technology. A successful code audit gives your client the opportunity to accurately assess the current state of their tools. It allows your clients the chance to evaluate recommendations, knowing that they were made with their business goals in mind.

It doesn’t just benefit them, though. It also benefits you.

Code audits give you an opportunity to develop new working relationships, and lay groundwork for a long-lasting partnership. The code audit is something you can build on with your client. Whether that leads to performing the recommendations you make or for future development overhauls, the options are endless! This is a low-commitment way to spark a relationship…if you do it right.

WordPress developers, WordPress eCommerce developers, Zao, Justin Sainton, Justin Sternberg, Cancer Tutor, best WordPress developers, what it's like to work with a WordPress developer, why choose Zao, Zao web development reviews, WordPress web development, code audit, hiring a WordPress dev, WordPress developer red flags, what is a code audit, how do i get a code audit, what is in a code audit, what's included in a code audit, how do i find a developer, finding a WordPress web developer, best WordPress web developers

Crucial Questions You Need to Ask Before Getting a Code Audit

Code audits are one of the main things Zao offers to our clients. Many of our clients are strategically looking at how they can expand their businesses, and a crucial aspect of that is making sure their technology is not hindering their growth.

There’s a lot of muddled information about what a code audit should look like, and many clients start their search for a code audit without any idea of what to expect, what questions to ask, or what they should be looking for when vetting developers to do the job.

Are you looking for a code audit? Here’s what you need to know and ask before you sign that check:

Code Audit Questions Clients Need to Ask

— What is the final deliverable I can expect from this audit?

Depending on your developer, the final deliverable can range from a simple confirmation that everything is working as it should to an in-depth delivery document that details what is working, what isn’t, and appropriate recommendations for improvement.

Nowadays, we all research what we’re spending our money on before we pay up. Whether that research is looking at Yelp reviews of local restaurants or comparing the best and the worst Amazon reviews on new products, we want to make sure we’re getting the best bang for our buck. So often, though, clients don’t ask what they can expect to receive when it comes to code audits.

Maybe you just want a developer to look things over and confirm if everything is solid. That’s great! If you find a developer that will simply send over an email with a 👍🏼 and “Everything’s cool,” then they’re a good choice for you!

code audit, getting a code audit, code audit my plugin, WordPress web developers, WordPress web development agencies, WordPress ecommerce developer, getting a developer, hiring a WordPress developer, should I get a code audit?, what is a code audit?

If you’re looking for a more intensive analysis of your current code, you’ll want to find a developer who provides that. Since there’s no industry standard on what deliverable comes with a code audit, you’ll need to investigate to find the developer that is providing what you want.

Here at Zao, our code audits come with an exhaustive document that assesses our clients’ current technology with a specific eye on their needs and challenges, and includes recommendations that pragmatically account for budget, time, and priority.

We also provide a timeline that, should the client choose to work with us on implementing those recommendations, gives a realistic perspective on how long it will take for those technical goals to be accomplished. Lastly, we detail in each recommendation how and why this change adds value to our clients’ businesses.

— What kind of code do you audit?

Investigating the details of what to expect from your code audit is vital because some developers only offer specialized code audits. Some developers exclusively audit plugins, themes, or apps, whereas others are focused on auditing detailed eCommerce integrations or your entire site.

If you know you’re looking for a specific kind of code audit, finding a developer who specializes and focuses on that kind of development is key. If you’re looking for a full site audit, but the developer you’ve contracted with focuses specifically on auditing Genesis themes, you may not get the most effective and comprehensive audit that you need.

— Can you provide more details on code audits you’ve done? Do you have a sample I can look at?

When you find out more about the scope of a developer’s experience and take a look at a code audit sample, you’ll get a better understanding what the end deliverable will be–even beyond the initial response. You’ll get a better idea of how your developer tackles code audits and communicates the end result.

This information is crucial, as it helps you understand what to expect of your developer, and can help you find a developer who communicates in a way that works best for you.

— What kinds of clients have you worked with in the past?

Most developers have worked with companies that span a broad range of industries, and can tackle projects in unfamiliar industries like a champ. However, knowing if their experience includes working with companies in your particular niche helps you know whether or not you’ll need to explain specific industry nuances to them.

Your technology needs to meet your business’ needs, and those can vary slightly from industry to industry. Knowing your developer’s history with your industry can help you determine what kind of crucial information you need to communicate–or whether your developer is already in a position to take on those challenges without extra explanation.

Red Flags

what questions to ask your developer, what is a code audit, when should i hire a developer, should i use WordPress, WordPress for eCommerce, WordPress web development, hire a WordPress developer, build a WordPress plugin, get a WordPress plugin for my business

In an initial introduction, everyone is on their best behavior.

Job interviews are like dating. As Chris Rock says, “When you meet somebody for the first time, you’re not meeting them, you’re meeting their representative.” You need to know what red flags to look for when seeking out a developer–and how to look past the friendly representative to make sure it’s going to be a good fit.

— A dev who doesn’t ask questions

If you’re talking with a developer about a code audit (and potentially more work beyond that) and they don’t ask detailed questions about what you’re looking for, what your current technology is, what kind of pain-points you’ve experienced, and more, you have a problem.

You want a developer who is invested in your company’s success, in solving your technical problems, and bringing value to your business. A developer who doesn’t ask questions isn’t going to know what you need, nor have the full understanding required to adequately assess what is going on with your site.

That’s one of the reasons that we ask detailed questions and make sure we know exactly where our clients are coming from. We want to make sure that we have specific notes on what to look for and what they’re trying to accomplish with their technology. Even if our clients don’t have the technical savvy to articulate what they need done, by knowing their goals, their struggles, and their technical history, we can help by capitalizing on our technical knowledge to come up with creative solutions.

— A dev who can’t tell you in concrete, clear terms what you’re going to get

There’s a reason asking about the deliverable is so important. Code audits, without planning, can beget intangible results. Unlike design, there’s no Photoshop mockup, or unlike copywriting, there’s no first draft. If a developer isn’t willing to say, “Here is the end result you can expect from me,” it’s a huge red flag.

hiring a WordPress dev, WordPress developer red flags, what is a code audit, how do i get a code audit, what is in a code audit, what's included in a code audit, how do i find a developer, finding a WordPress web developer, best WordPress web developers

Your developer needs to be able to set your expectations accordingly. You need to know what you are paying for at the end of this–and a developer who cannot tell you what you are getting for your money is not one you should hire.

We know vetting developers who, as far as you may be concerned, basically work magic on the internet, can be stressful. It doesn’t have to be, though. Now that you’re armed with these questions and red flags to look out for, you can assess which developer is going to be able to provide the code audit you need.

Have any other questions about code audits that we haven’t covered? Drop ‘em in the comments; we’re here to help!