
Insert CSS selectors into the markup to highlight a specific shipping method.
A local client bakes and delivers sourdough bread. He also offers a free collection option but would rather that customers would not choose it (it’s primarily there for long time loyal customers).
I looked at the markup on the Cart and Checkout pages and the shipping methods do *not* have any css classes! Their label elements have the ‘for‘ attribute set but it’s doesn’t appear to be useful. I tried to use CSS with wildcards but it didn’t work.
label[for=shipping_method_*_free_shipping*] { font-size: 60%; }
In a template file
I searched through the WooCommerce source for “woocommerce-shipping-methods” (the class of the ul element around the list of shipping methods) and found it in woocommerce/templates/cart/cart-shipping.php.
I was disappointed to see that there were no apply_filters() calls around the shipping methods items, only a do_action() call after them. The do_action() call is given the same information ($method and $index) that is used to create the shipping method label markup so I could work with this.
A touch of CSS
My solution is not pretty but it works. In the do_action() function I add a <style> block with a selector to target the appropriate shipping method label. In my case I was looking to change the font size of the only free shipping method so the code checks for the $method->method_id. To minimise the amount of CSS in the plugin I use a CSS variable for the font-size. The variable must be defined in another CSS file.
If other styles need to be set they will have to be added to the code. The lack of CSS classes on the label element is restrictive.

The code
Enhancements
It would be a great help if the label elements had CSS classes e.g. “shipping_method free_shipping“. I might submit a pull request to WooCommerce to suggest this.
For my code, shoving <style> blocks into the markup is a bit ugly and not a good practice. If I converted the code to a PHP class I could store the selectors and add the <style> block to a wp_footer action. That’s for another day.
Leave a Reply