根据Woocommerce中的结帐字段显示隐藏付款网关[关闭]

问题描述 投票:0回答:1

在Woocommerce结帐页面,我试图隐藏一些支付网关,当“运送到不同的地址?”时,只保留“货到付款”付款方式(COD)。检查。

我试过Conditionally hiding et showing payment gateways有一些变化,但我没有工作。我也试过了不同的答案代码而没有成功。

如何“运送到不同的地址?”时如何仅保留COD付款?检查?

任何帮助表示赞赏。

php ajax wordpress woocommerce checkout
1个回答
0
投票

以下代码将隐藏所有支付网关,但“货到付款”(COD)时“运送到其他地址?”已选中(并显示发货结帐字段):

// The jQuery Ajax request
add_action( 'wp_footer', 'checkout_billing_area_script' );
function checkout_billing_area_script() {
    // Only checkout page
    if( is_checkout() && ! is_wc_endpoint_url() ):

    // Remove "ship_different" custom WC session on load
    if( WC()->session->get('ship_different') ){
        WC()->session->__unset('ship_different');
    }
    // jQuery Ajax code below
    ?>
    <script type="text/javascript">
    jQuery( function($){
        if (typeof wc_checkout_params === 'undefined')
            return false;

        var a = '#ship-to-different-address-checkbox', b = '';

        // Ajax function
        function triggerSTDA( value ){
             $.ajax({
                type: 'POST',
                url: wc_checkout_params.ajax_url,
                data: {
                    'action': 'ship_different_address',
                    'ship_different': value,
                },
                success: function (result) {
                    $('body').trigger('update_checkout');
                    console.log(result); // For testing (to be removed)
                }
            });
        }

        $(a).on( 'change', function(){
            b = $(this).prop('checked') === true ? 'yes' : 'no';
            triggerSTDA( b );
        });
    });
    </script>
    <?php
    endif;
}

// The Wordpress Ajax PHP receiver
add_action( 'wp_ajax_ship_different_address', 'get_ajax_ship_different_address' );
add_action( 'wp_ajax_nopriv_ship_different_address', 'get_ajax_ship_different_address' );
function get_ajax_ship_different_address() {
    if ( isset($_POST['ship_different']) ){
        WC()->session->set('ship_different', esc_attr($_POST['ship_different']));
        echo $_POST['ship_different'];
    }
    die();
}

// Show/hide payment gateways
add_filter( 'woocommerce_available_payment_gateways', 'conditionally_hide_payment_gateways', 100, 1 );
function conditionally_hide_payment_gateways( $available_gateways ) {
    if( WC()->session->get('ship_different') == 'yes' ) {
        foreach( $available_gateways as $gateways_id => $gateways ){
            if( $gateways_id !== 'cod' ) {
                unset($available_gateways[$gateways_id]);
            }
        }
    }
    return $available_gateways;
}

代码位于活动子主题(或活动主题)的function.php文件中。经过测试和工作。

© www.soinside.com 2019 - 2024. All rights reserved.