在Woocommerce结帐中添加特定选定送货选项的正文类

时间:2018-02-19 10:25:24

标签: php jquery css wordpress woocommerce

如果在Woocommerce结帐页面上访问者位于特定的送货选项中,我会尝试将类添加到页面正文中。我已经完成了以下但是它没有添加课程?有人可以帮忙吗?

add_filter( 'body_class', 'bbloomer_wc_product_cats_css_body_class' );

function bbloomer_wc_product_cats_css_body_class( $classes, $available_gateways ){

    global $woocommerce;
    $chosen_titles = array();
    $available_methods = $woocommerce->shipping->get_packages();
    $chosen_rates = ( isset( $woocommerce->session ) ) ? $woocommerce->session->get( 'chosen_shipping_methods' ) : array();

    foreach ($available_methods as $method)
           foreach ($chosen_rates as $chosen) {
                if( isset( $method['rates'][$chosen] ) ) $chosen_titles[] = $method['rates'][ $chosen ]->label;
            }
    if( in_array( 'Delivery price on request', $chosen_titles ) ) {
    $custom_terms = get_the_terms(0, 'product_cat');
    if ($custom_terms) {
      foreach ($custom_terms as $custom_term) {
        $classes[] = 'delivery-not-available';
      }
    }       
    }
  return $classes;
}

1 个答案:

答案 0 :(得分:1)

  

由于这是客户端的直播活动,因此只能使用Javascript / jQuery

由于您未按要求提供交货价格的送货方式ID'运送方法,php代码会在将它传递给jQuery代码之前找到它。根据要求提供交货价格'将是所选择的方法,班级'交付 - 不可用'将在结帐页面上附加在正文现有的课程中。

代码:

add_filter( 'wp_footer','custom_product_title_script' );
function custom_product_title_script(){
    if( ! is_checkout() ) 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( 'Delivery price on request' == $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 = 'delivery-not-available',
                    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
}

代码进入活动子主题(或活动主题)的function.php文件。

经过测试和工作。