我正在尝试学习一些更高级的WordPress,我使用并改编了代码段,但无法理解其中的某些来源。该代码段适用于WooCommerce,并在“免费送货”可用时隐藏其他送货方式。
它看起来像是一个循环,使用名为$ rates的变量,但我在Woo Dev Docs中找不到有关此变量的任何内容。我以为它可能是一个类的实例,但再次找不到任何可能有用的信息。根据下面的代码片段,有人可以告诉我$ rates的来源,价格以及它的声明位置吗?
add_filter( 'woocommerce_package_rates', 'bbloomer_unset_shipping_when_free_is_available_all_zones', 10, 2 );
function bbloomer_unset_shipping_when_free_is_available_all_zones( $rates, $package ) {
$all_free_rates = array();
foreach ( $rates as $rate_id => $rate ) {
if ( 'free_shipping' === $rate->method_id ) {
$all_free_rates[ $rate_id ] = $rate;
break;
}
}
if ( empty( $all_free_rates )) {
return $rates;
} else {
return $all_free_rates;
}
}
答案 0 :(得分:0)
过滤器挂钩woocommerce_package_rates
是WC_Shipping
类的一部分。如果您查看此钩子所在的the source code,则$rates
变量实际上等于$package['rates']
:
$package['rates'] = apply_filters( 'woocommerce_package_rates', $package['rates'], $package );
$package
变量数组存储要装运的包装和获取报价的软件包。
您可以在StackOverFlow中查看the list of questions/answers that are using this hook,以更好地了解其用法。
答案 1 :(得分:0)
$ rates是由calculate_shipping_for_package()
中的函数woocommerce/includes/class-wc-shipping.php
生成的。您可以在下面的功能中看到过滤器woocommerce_package_rates
public function calculate_shipping_for_package( $package = array(), $package_key = 0 ) {
// If shipping is disabled or the package is invalid, return false.
if ( ! $this->enabled || empty( $package ) ) {
return false;
}
$package['rates'] = array();
// If the package is not shippable, e.g. trying to ship to an invalid country, do not calculate rates.
if ( $this->is_package_shippable( $package ) ) {
// Check if we need to recalculate shipping for this package.
$package_to_hash = $package;
// Remove data objects so hashes are consistent.
foreach ( $package_to_hash['contents'] as $item_id => $item ) {
unset( $package_to_hash['contents'][ $item_id ]['data'] );
}
$package_hash = 'wc_ship_' . md5( wp_json_encode( $package_to_hash ) . WC_Cache_Helper::get_transient_version( 'shipping' ) );
$session_key = 'shipping_for_package_' . $package_key;
$stored_rates = WC()->session->get( $session_key );
if ( ! is_array( $stored_rates ) || $package_hash !== $stored_rates['package_hash'] || 'yes' === get_option( 'woocommerce_shipping_debug_mode', 'no' ) ) {
foreach ( $this->load_shipping_methods( $package ) as $shipping_method ) {
if ( ! $shipping_method->supports( 'shipping-zones' ) || $shipping_method->get_instance_id() ) {
$package['rates'] = $package['rates'] + $shipping_method->get_rates_for_package( $package ); // + instead of array_merge maintains numeric keys
}
}
// Filter the calculated rates.
$package['rates'] = apply_filters( 'woocommerce_package_rates', $package['rates'], $package );
// Store in session to avoid recalculation.
WC()->session->set(
$session_key, array(
'package_hash' => $package_hash,
'rates' => $package['rates'],
)
);
} else {
$package['rates'] = $stored_rates['rates'];
}
}
return $package;
}