Tarik Hamilton

Create Placeholders for WooCommerce Fields From the Labels #DRY

Not into labels? Would you rather people learn who you are by what’s inside? Me too. I project these feelings onto my forms. I’m a fan of placeholder text as input labels and so is most of the internet. Why take up more vertical space than necessary?

WooCommerce puts the labels on the outside in a label tag, but offers an easy way to change placeholders with a filter. The caveat is you have to do each field, as shown below from the docs.

function custom_override_checkout_fields( $fields ) {
     $fields['order']['order_comments']['placeholder'] = 'My new placeholder';
     $fields['order']['order_comments']['label'] = 'My new label';
     return $fields;
}

So, for our purposes, this could be made a bit easier.

$fields['billing']['billing_first_name']['placeholder'] = $fields['billing']['billing_first_name']['label'];

Still too much typing. Here’s what I came up with. I hope it saves you time!

Staying DRY

This goes through each field and assigns the placeholder the label value. There are a few exceptions where there might not be a label or the label should be different. Just add it to the exceptions array. `billing_address_2` doesn’t have a label, so I wrote one in for the placeholder.

As for CSS, you can select the labels and apply these screenreader properties, this way they’re gone, but not forgotten. 😉


.woocommerce form .form-row label {
    position: absolute;
    width: 1px;
    height: 1px;
    padding: 0;
    margin: -1px;
    overflow: hidden;
    clip: rect(0,0,0,0);
    border: 0;
}

Did this help? Leave a comment and let me know.