WooCommerce无法优先考虑表价运输方法,所以我试图自己做,但失败了。
我试着在我认为已经确定的时候添加一个动作,但它不起作用。以下是我尝试过的(我只想使用可用运输方法数组中的第一种运输方法):
function reset_default_shipping_method() {
$available_methods = WC()->shipping->packages[0]['rates'];
$chosen_method = key($available_methods);
WC()->session->set( 'chosen_shipping_methods', $chosen_method );
}
add_action('woocommerce_shipping_method_chosen', 'reset_default_shipping_method');
我已经测试了$available_methods
和$chosen_method
,它们都按预期呈现(在页面中运行时),但是,一旦我将其添加到动作woocommerce_shipping_method_chosen
中,它似乎就不会更新。
例如,如果我通过一个不同的钩子运行这个:
function output_to_footer() {
if ( current_user_can( 'administrator' ) ) :
$current_method = WC()->session->get( 'chosen_shipping_methods');
$available_methods = WC()->shipping->packages[0]['rates'];
$chosen_method = key($available_methods);
WC()->session->set( 'chosen_shipping_methods', $chosen_method );
print "'n".'-----'."'n";
print_r($current_method);
print "'n".'-----'."'n";
print_r($available_methods);
print "'n".'-----'."'n";
print_r($chosen_method);
print "'n".'-----'."'n";
endif;
}
add_action('print_footer_messages', 'output_to_footer');
看起来一切都在做它应该做的事情,但当我从动作中运行它时:woocommerce_shipping_method_chosen
它"似乎"在做一切,但运输无线电仍然设置为旧的运输方法?
-----大堆([0]=>table_rate-5:70)-----大堆([table_rate-7:72]=>WC_Shipping_rate对象([id]=>table_rate-7:72[label]=>澳大利亚注册邮政(2至8个工作日)[成本]=>4.0909[tax]=>数组([1] =>0.40909)[method_id]=>table_rate)[table_rate-8:90]=>WC_Shipping_rate对象([id]=>表日期8:90[label]=>跟踪和运费保险[成本]=>20.055881818182[tax]=>数组([1] =>2.0055881818182)[method_id]=>table_rate)[table_rate-5:70]=>WC_Shipping_rate对象([id]=>table_rate-5:70[label]=>全国交付(5至12个工作日)[成本]=>0[tax]=>数组()[method_id]=>table_rate)[local_pickup]=>WC_Shipping_Rate对象([id]=>local_pickup[label]=>本地取货[成本]=>0[tax]=>数组()[method_id]=>local_pickup))-----表_日期7:72-----
我已经为此工作了一整天,感觉离解决方案不远了。希望这里有人能帮忙。
woocommerce_shipping_chosen_method
是一个过滤器挂钩,而不是一个操作挂钩。尝试以下代码
function reset_default_shipping_method( $method, $available_methods ) {
// If the shipping method has been chosen don't do anything
if ( ! empty( $method ) ) {
return $method;
}
// add code to set 'Table Rate' as the default shipping method
$method = 'table_rate-5';
return $method;
}
add_filter('woocommerce_shipping_chosen_method', 'reset_default_shipping_method', 10, 2);
p.S:我已经将table_rate-5
硬编码为默认方法,为您提供要点,所以请将其更改为所需的方法。理想情况下,您需要编写代码,看看您想要设置为默认值的方法在$available_methods
中是否可用,然后相应地工作。
这是我最终使用的,它按要求工作:
/*=Use the shipping method filter to set the "selected" shipping method to
* the first (default) method in the list
**************************************************************************/
function oley_reset_default_shipping_method( $method, $available_methods ) {
$method = key($available_methods);
return $method;
}
add_filter('woocommerce_shipping_chosen_method', 'oley_reset_default_shipping_method', 10, 2);
(注意:这是有效的,因为我想要的运费实际上是列表中的第一个,但默认情况下没有选择)