在 WooCommerce 中重新排序国家/地区结帐国家/地区选择 2 个下拉列表

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

描述:

我正在尝试自定义 WooCommerce 结帐页面上帐单地址(帐单国家/地区)下拉菜单中的国家/地区顺序。为此,我使用 woocommerce_checkout_fields 过滤器来调整下拉菜单中国家/地区的顺序。

当我尝试进行这些自定义时,出现了问题:帐单地址(帐单国家/地区)的下拉菜单按预期工作,以所需的顺序显示国家/地区。然而,这似乎停用了 Select2 功能,该功能通常用于提供增强的下拉体验。

我的做法:

这是我的代码摘录,展示了帐单地址下拉菜单中国家/地区顺序的调整:

add_filter( 'woocommerce_checkout_fields', 'customize_country_dropdown_order' );
function customize_country_dropdown_order( $fields ) {

    $first_countries = array(
        'DE' => 'Germany',
        'AT' => 'Austria',
        'CH' => 'Switzerland',
    );

    $rest_countries = array_diff( WC()->countries->get_allowed_countries(), $first_countries );

    // Combine the first countries and the rest with a separator
    $custom_country_list = array_merge( $first_countries, array( '-' => '------------' ), $rest_countries );

    // Update the order of the billing and shipping country dropdowns
    $fields['billing']['billing_country']['type'] = 'select';
    $fields['billing']['billing_country']['options'] = $custom_country_list;

    $fields['shipping']['shipping_country']['type'] = 'select';
    $fields['shipping']['shipping_country']['options'] = $custom_country_list;

    return $fields;
}

我的问题:

自定义国家/地区顺序后,如何重新激活帐单地址下拉菜单(帐单国家/地区)的 Select2 功能?我可以使用特定的方法或途径来实现这一目标吗?

php wordpress woocommerce jquery-select2 checkout
1个回答
0
投票

您只需添加以下代码片段即可返回jQuery Select2 下拉列表:

add_action( 'woocommerce_checkout_init', 'enable_back_selectWoo_on_countries_dropdowns' );
function enable_back_selectWoo_on_countries_dropdowns() {
    wc_enqueue_js("$('#billing_country,#shipping_country').selectWoo();");
}

注意:这里我们使用 selectWoo,Select2 的 WooCommerce 分支。

您将得到:

此外,您可以使用以下方法来简化/压缩代码:

add_filter( 'woocommerce_checkout_fields', 'customize_country_dropdown_order' );
function customize_country_dropdown_order( $fields ) {
    // Merge sorted countries, with unsorted ones
    $countries_array = array_merge( 
        array(
            'DE' => 'Germany',
            'AT' => 'Austria',
            'CH' => 'Switzerland',
            '-'  => '------------',
        ),
        WC()->countries->get_allowed_countries(), 
    );

    // Change field type from "country" to "select"
    $fields['billing']['billing_country']['type'] = $fields['shipping']['shipping_country']['type'] = 'select';
    // Set sorted countries options
    $fields['billing']['billing_country']['options'] = $fields['shipping']['shipping_country']['options'] = $countries_array;

    return $fields;
}
© www.soinside.com 2019 - 2024. All rights reserved.