CSS Grid, Front-end development, front-end development tips and tricks

Why CSS Grid Should Be In Your Front-End Development Toolbox

I recently had the privilege of taking Wes Bos’ free course on CSS Grid (thanks, Mozilla!). If you’re a front-end developer, this is a must take course. At first, I was a little skeptical about CSS Grid given how much I love Flexbox. Additionally, I wasn’t seeing support for Android’s default browser when I’d checked it before, but according to caniuse.com at the time of this post, Grid has 86.59% browser support and Android is now golden.

While CSS Grid is not as supported as Flexbox, it pretty much has similiar support for the vast majority of our target audience. Opera Mini is the main browser that has no support for Grid. According to Rad Devon, most Opera Mini users are in Africa for users with incredibly low data plans (think 10 MB per month). So it feels pretty safe to me, when it comes to the clients we’re working with, to view CSS Grid as a viable option.

I primarily work in the WordPress realm, so I’m constantly dealing with themes and child themes. I was especially encouraged by Wes’ full bleed episode which feels very applicable to doing some really neat layouts especially with dynamic content that a user is populating on their pages or posts. Full Bleed layouts in the past were either a nightmare to make with all sorts of wrappers, or very hacky with negative margin. With CSS Grid we can quickly and easily allow for full content while having the majority of the layout support the optimal text length.

Continue Reading

troubleshooting print stylesheets, troubleshooting in CSS, troubleshooting CSS, CSS tutorials, CSS print stylesheet tutorials, WordPress tutorials

How to Troubleshoot Print Style Sheets: Common Problems and Solutions

If any of you have played around with a print style style sheet on a complex theme or site you might already be familiar with the fact that print CSS does not always operate the way you would expect or desire. If you have not yet experienced the familiar urge to ram your head through your computer screen, I hope to save you from that experience with a few tips and tricks I picked up while learning to troubleshoot print style sheets.

Before we jump in, I want to ensure you’ve got some useful tools right off the bat to help set you up for success.

What you need

First, make sure you’re working on a browser that allows you to turn on a print emulator. This will make troubleshooting go a lot faster. However, be forewarned, while the print emulator shows the elements you will be printing and their style sheet rules, it does not necessarily visually represent perfectly what the printed page will actually look like. Frequently check your changes by either printing or viewing/downloading them as a PDF to confirm you’re getting the desired results. You will be sorely disappointed to get things pixel perfect in an emulator only to discover the printed result is vastly different.

Additionally, make sure your browser’s print scale is set to 100%. While you don’t have control over what your users will do with their browsers, there is a good chance many users won’t have changed their browser print settings. Therefore, you want to save yourself any headaches where you think you’ve developed correctly only to discover that you had been in the wrong scale.

how to troubleshoot print style sheets, printing style sheets in WordPress, printing style sheets from WordPress, working in CSS, CSS troubleshooting, CSS tutorials

I pretty much exclusively develop on Chrome and then check on other browsers to ensure things are working as desired. This Stack Overflow will show you how to turn on Chrome’s print emulator in various different chrome versions. Google “Print Emulator [browser name]” if you prefer to work in something besides Chrome.

Below is a list of issues I have commonly faced and some solutions that rectified them. I hope they can save you time and hours of googling or shooting in the dark.

Continue Reading

Using the WooCommerce API with wp-api.js

As of WordPress 4.7, we’ve had a really fantastic, fully featured REST API in WordPress. It is relatively well-known that the infrastructure for the API was introduced in WordPress 4.4, with the content endpoints being introduced in 4.7.

What is somewhat less well-known is that 4.7 also shipped with a Backbone.js client you can use to interface with the core API.  It’s super simple to enqueue:

wp_enqueue_script( 'wp-api' );

Using it for core objects is pretty straight-forward:

var post - new wp.api.models.Post( { id : 2 } );
alert( post.attributes.title.rendered ); // Renders "rendered" title of post.

But what if you want to use it with non-core objects that are in custom namespaces, or maybe not even on your own site? Thinking that you’ll probably have to write some PHP, maybe your own library or framework for interfacing with these, and your own JS models? Ugh, amirite?

Good news! None of that is necessary.

Continue Reading

WordPress tutorials, CMB2 tutorials, CMB2 meta fields, CMB2 how to, CMB2 WordPress plugin,

How to Save a Backslash (\) to CMB2 Meta Fields

Recently, we had a user request that their backslashes be preserved when saving their CMB2 fields. Typically, when a user wants non-standard sanitization, our canned response is to use the provided field parameter sanitization override, 'sanitization_cb'. If you’re not aware of this field parameter (and it’s cousin, 'escape_cb'), let me explain a bit.

By default, CMB2 does quite a bit of heavy-lifting for you when it comes to sanitizing your users’ input, as well as escaping that value for proper display. This is just one of the aspects of CMB2 that I appreciate; that I don’t have to “think” about the sanitization/escaping of my fields.

“It just works.”

Except, of course, when it doesn’t.

Continue Reading

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="{{ data.id }}">
        <# if ( data.status.name ) { #>
            <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.open }}}
                    {{ data.status.name }}
                {{{ 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 data.open 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 

WP eCommerce: How to add a ZIP Code Lookup to your Checkout

We get loads of requests for customizations to different eCommerce platforms on WordPress.  One that we receive on a super regular basis is for the ability to auto-populate the city, state and country just by entering the ZIP Code.  This is a very US-centric feature, though it could be ported to any country.  The concept really favors those businesses that sell primarily within their own country.  That said, this segment comprises a very large portion of the eCommerce space.

So that said – how would you do this?  It’s actually pretty easy.  From a UX standpoint, you want to be sure that you’re showing the ZIP Code before you show the other fields – otherwise, it sort of defeats the purpose.  WP eCommerce makes this super easy, but every platform is different.

Next, you’ll want to connect with a ZIP Code API of your choice.  There are myriad different APIs to choose from, pick your favorite or whatever fits best for your purposes.  For today, I’m going to use Zippopotamus. What I like about that service is that it actually works in over 60 different countries, not just the US, even though that’s our focus for today.

A user experience that I’ve come to really enjoy is the ability to fill in a ZIP Code, and then have it auto-fill and auto-show the city, state and country.  The constant refrain against trying to be smart about ZIP Codes is “What if you get it wrong? What about ZIP Codes that cover multiple cities?  What if the API fails?”

A simple UX is the key to all of these edge cases.  Regardless of success or failure, simply show the extra fields once a response is received – or if none can be received at all.  If it happens to return nothing, or the wrong thing, the user can simply fill in the right thing.  But it’s a great improvement for the vast majority of visitors to your site.  Now, for some code.

The code above is pretty well self-contained and self-explanatory. It’s not the prettiest thing ever, or the most complete, but it gets the job done. In essence, we’re simply adding three functions.  One to show the city/state/country, one to hide it, and one to ping the API.  We’re not doing any clever error handling.  We’re simply pinging the API, and showing all the fields, no matter what.  If we get a successful response, we’re filling in the fields with that information.

You’ll notice, if you’re familiar with WP eCommerce, that we’re not targeting any fields that exist in the stable version that exists in the wild today. We have a phenomenal new release coming out, version 4.0.  It includes what I believe is the most usable checkout experience in any eCommerce platform for WordPress.  We’re targeting elements within that new theme engine.  Be sure to check that out.

With those ~35 lines of code, we have the experience you witness below.  A totally usable



WP eCommerce: How to Enable the Test Gateway for Admins Only

From time to time, I find myself needing to do test purchasing on a live site. Generally speaking, it’s because there is something occurring outside the payment flow on a live site that cannot be replicated locally. The following code ensures that the test gateway is enabled only for logged-in admin users. Hope it’s helpful!

add_filter( 'option_custom_gateway_options', function( $gateways ) {

    if ( current_user_can( 'manage_options' ) && ! in_array( 'wpsc_merchant_testmode', $gateways ) ) {
        $gateways[] = 'wpsc_merchant_testmode';

    return $gateways;
} );

Git Bisect and Why it is Amazing

Had a client email me recently, mildly concerned, as an update to WP eCommerce broken his search layout. I told him that I couldn’t think of anything between the latest version and the prior version that would have caused any such thing, but I’d be more than happy to check it out.

Initially, if I’m being quite honest, I just assumed it was user error.  It’s easy to mis-configure things, set up a theme wrong, etc. Any number of things can go wrong. But, I dug in and in fact, we had broken it.  I didn’t recall any changes in the 913 commits between the two changes.

With nothing obvious, and 913 commits between release – what was a developer to do?  Enter, git bisect.

Git bisect is amazing. Prior to using it, you might think to yourself,

“Hmm, self, I suppose I can checkout a few different commits, figure out a commit where it works, and one where it doesn’t, and sort of narrow down a range until I find it.”

And that would be a really good thought.  But it would take you, a human, waaaaaaay longer than git would take.  That very thought you had? That’s what git bisect does.  Imagine you have the master branch, latest commit checked out.  You know that a previous version branch worked fine.  Check this out.

git bisect start
git bisect good
git bisect bad branch-

And boom, you’ve started down the path. Git will analyze how many revisions exist between good and bad, split the difference, and checkout that commit. Then, test to see if the bug still exists. If it does, git bisect bad. If not, git bisect good. It will keep narrowing down the commits until it finds the precise commit that caused the issue.

In case you remain unconvinced – remember – I was able to wade through 913 commits to find the single commit that caused a bug in a piece of software that spans hundreds of files and over 150,000 lines of code.

It took about three minutes.

Git bisect is amazing.

How To: Remove Shipping Calculator from WP eCommerce

From time to time, we get people asking how they can remove the Shipping Calculator feature in WP eCommerce.  You’ve probably come across these before: before calculating shipping, you have to enter your ZIP code or state or something like that.  Pretty standard fare.

The problem, of course, is that it can be an unnecessary extra step, causing friction in the checkout process.  For example, it’s totally unnecessary if you only ship to one country and ship with a flat rate to that country, it makes no sense to have a shipping calculator.   So – let’s dig in!

If you haven’t moved your shopping cart template file to your active theme folder, now’s the time to do that :)  In a normal installation, you’ll have a shipping calculator that looks something like this:


Step 1: Presentation

The first step is removing the calculator from your theme.  There’s not a single chunk of code to remove, but a few.  Thankfully, they’re all right around the same place.

  1. Remove the “Calculate Shipping Price” header.
  2. Remove built-in error/notice conditions, country and ZIP drop-downs.

At this point, the shipping calculator should be visibly absent.  Woohoo!

Step 2: Functional Logic

Even though we’re looking good now, we’re not working good.  That’s a problem.  The first thing you’ll notice is that when you hit purchase, you get scrolled back to the top of the page with a message that says you need to calculate shipping.  While we have filters that control whether or not you should force that sliding UX, we have even better filters to control whether or not to force a recalculation.  The following filter in a plugin

add_filter( 'wpsc_needs_shipping_recalc', '__return_false' );

This gets us one step closer, but astute observers may note that shipping quotes no longer show up.  This is because none are calculated.  The following code ensures a rate is calculated:

add_action( 'template_redirect', function() {
    if ( is_page( wpsc_get_the_post_id_by_shortcode( '[checkout]' ) ) ) {
} );

If you’re only using a single shipping method with a single rate (as most folks who request this seem to be), you’re all set.  The steps above are all you need to do to kill off the shipping calculator for good :)

If you’re using multiple shipping methods?  Well, that gets trickier, and depends on which methods you’re using.  If this is an issue you’re facing, I’d be more than happy to chat with you about it.

Give me a call

How To: Set the Default Shipping Country in WP eCommerce

There are a few really great scenarios to set a default shipping country for your WP eCommerce shop.  In a past iteration, we actually defaulted to the base country and region of the shop itself.  There was some decent, though flawed and short-sighted logic behind this.  We eventually reverted that behavior in favor of requiring users to choose their own shipping location.

While this behavior is more intuitive, from time to time, we do get users asking for the ability to default to a specific country.  While the previous behavior is sometimes requested, other scenarios might include defaulting to the country where you receive most of your orders from.  This could vary wildly depending on season or product line.  The code below is a helpful start to defaulting to any country you desire.  Note: The filter being used should return a country’s ISO code.

You’ll notice we’re using the variable filter for the visitor meta API that is specific to the key being called.  There is also the more generic wpsc_get_visitor_meta filter, but with the variable filter, we don’t need to check for the key being called.