对于WooCommerce,我使用插件创建了一个送货方法,并try 使用以下代码更改订单

add_filter('woocommerce_package_rates', 'mostrar_metodo_personalizado', 10, 2);
function mostrar_metodo_personalizado($rates, $package) {
    $nombre_del_metodo = 'Zona 1';

    if (isset($rates[$nombre_del_metodo])) {
        $rates[$nombre_del_metodo]->sort_order = 1;
    }

    return $rates;
}

但这不管用,有人能解释一下我哪里做错了吗? 谢谢

推荐答案

Normally this can be done in your WooCommerce shipping settings. You can sort shipping methods by dragging the little icon enter image description here located on the left of each shipping method:

enter image description here

这在大多数情况下都应该有效.


You can do it also programmatically.

1) Finding the correct shipping method keys

首先,由于您没有在代码中使用the right shipping methods key reference,因此要查找正确的发货方法关键字引用,请使用以下代码:

add_action('wp_footer', 'wp_footer_test_output', 10);
function wp_footer_test_output() {
    if( current_user_can('administrator') ) {
        echo '<pre>';
        foreach ( WC()->session->get('shipping_for_package_0')['rates'] as $rate ) {
            printf('For this <strong>"%s"</strong> shipping method, the key is: <code>%s</code><br>', $rate->label, $rate->id);
        }
        echo '</pre>';
    }
}

然后在您的网站中,将产品添加到购物车并转到购物车页面.在页脚上,您将看到显示了您的所有活动发货方法及其参考代码.

2) Sorting displayed shipping methods

获得所需送货方式的正确密钥后,即可删除代码并使用下面的送货方式密钥.

以下代码将首先移动所需的显示运输方式:

add_filter('woocommerce_package_rates', 'sort_shipping_methods', 10, 2);
function sort_shipping_methods($rates, $package) {
    // Here define the correct shipping method key
    $shipping_method_key = 'flat_rate:9';

    if (isset($rates[$shipping_method_key])) {
        $rates1[$shipping_method_key] = $rates[$shipping_method_key];
        unset($rates[$shipping_method_key]);
    }
    return isset($rates1) ? array_merge($rates1, $rates) : $rates;
}

代码位于您的子主题的unctions.php文件中(或在插件中).经过测试和工作.

Important:您必须清空购物车才能刷新发货方法缓存.

相关帖子:

Php相关问答推荐

用户信息更新期间Laravel邮箱验证问题

邮箱打开跟踪器不工作时发送邮件使用laravel调度程序

如何更改数据表行背景 colored颜色

PHP MySQL求和子树并与父树累加

在WooCommerce管理中 for each 运输方法设置添加自定义字段

如何从该字符串中删除这些图标转换的ASCII问号字符?

如何在微软图形API中使用用户S访问令牌或基于租户ID的访问令牌?

根据发货类别在WooCommerce产品页面中显示快捷代码

如何在laravel中添加延迟?

Regex:高级删除单行PHP注释

Laravel withOnly不限制查询

如何使用 PHP 创建简化的 twig 替换?

由于 PHP 版本不受支持,如何终止 PHP 脚本?

在 WooCommerce wc_get_products 函数中处理自定义分类法

Laravel Eloquent(where 子句)

PHP:如何将多列sql查询结果转换成数组

Laravel auth()->id() 在生产服务器中不工作

yii2 sql迁移覆盖新更改的记录

无法在 Laravel 10 中安装 jenssegers/mongodb

Laravel 响应 html 默认页面忽略控制器