在 WooCommerce 结帐中为特定选择的送货方式添加 body class

Add a body class for specific chosen shipping method in WooCommerce checkout

基于答案代码,我已经使用下面的代码片段一段时间了:

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
}

但是我注意到它不再在页面加载时触发,我必须刷新页面才能触发它,这使它变得无用。

用例基本上是加载 body 标签 (weekend-selected),然后隐藏(使用 CSS)日历上的某些日期。

首先我认为这是因为在添加地址之前没有加载运输选项所以我预填了必填的地址字段以查看这是否是问题所在但同样的事情发生了,我必须刷新页面以获取代码触发。

尝试以下简单轻便的方法(不使用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;
}

代码进入活动子主题(或活动主题)的 functions.php 文件。它应该更好用。

相关: