Reputation: 57
Based on Add a body class for specific selected shipping option in Woocommerce checkout answer code, I have been using the following code snippet for some time:
add_filter( 'wp_footer','weekend_selected' );
function weekend_selected(){
if( ! is_page( 8 ) ) return; // only on checkout
$method_id = "''";
// Find the Shipping Method ID for the Shipping Method label name 'Delivery price on request'
foreach( WC()->session->get('shipping_for_package_0')['rates'] as $rate_key => $rate ){
if( 'Saturdays DPD' == $rate->label ){
$method_id = $rate_key;
break;
}
}
?>
<script type="text/javascript">
(function($){
// variables initialization
var a = 'input[name^="shipping_method[0]"]',
b = a+':checked',
c = 'weekend-selected',
d = '<?php echo $method_id; ?>';
if( $(b).val() == d )
$('body').addClass(c);
else
$('body').removeClass(c);
$( 'form.checkout' ).on( 'change', a, function() {
if( $(b).val() == d )
$('body').addClass(c);
else
$('body').removeClass(c);
});
})(jQuery);
</script>
<?php
}
However I have noticed that it does not trigger anymore on page load, I have to refresh the page for it to trigger which is making it useless.
The use case is basically to load a body tag (weekend-selected) which then hides (with CSS) certain days on a calendar.
First I thought it was because the shipping options were not loading before an address was added so I prefilled required address fields to see if this was the problem but the same thing happens, I have to refresh the page for the code to trigger.
Upvotes: 3
Views: 892
Reputation: 253968
Try the following simple and light way (without using Jquery):
add_filter( 'body_class', 'add_shipping_classes_to_body_class' );
function add_shipping_classes_to_body_class( $classes ) {
// only on checkout page
if( ! ( is_checkout() && ! is_wc_endpoint_url() ) )
return;
$chosen_method = WC()->session->get('chosen_shipping_methods')[0];
$shipping_rates = WC()->session->get('shipping_for_package_0')['rates'];
if( 'Saturdays DPD' === $shipping_rates[$chosen_method]->label ){
$classes[] = 'weekend-selected';
}
return $classes;
}
Code goes in functions.php file of the active child theme (or active theme). It should better works.
Related: Add shipping class to body class on WooCommerce checkout page
Upvotes: 3