我编写了以下函数,用于按最低价格和库存设置默认 Woocommerce 变化。 但问题是,当用户第二次请求产品页面时,此功能可以正常工作! 当第一次显示产品时,默认变体无法正常工作! 在第一次请求后更新可变产品的默认变体!
add_action( 'woocommerce_before_variations_form', 'set_default_variation_job' );
function set_default_variation_job() {
$product_id = get_the_ID();
$product = wc_get_product($product_id); // Get the variable product object
// Only for variable products & Check if default variation has been updated
if ( $product->is_type( 'variable' ) ) {
$active_prices = $product->get_variation_prices()['price']; // Array of variation Id / active price pairs
foreach ($active_prices as $key => $value) {
$variation = wc_get_product($key);
if($value == "0" || !$variation->is_in_stock()){
unset($active_prices[$key]);
}
}
asort($active_prices, SORT_NUMERIC);
$variations_ids = array_keys($active_prices); // Array of variations IDs
$variation_id = strval($variations_ids[0]); // Get the variation with the Lowest price
$variation = wc_get_product( $variation_id ); // Get an instance of the WC_Product_Variation object
$default_attributes = $variation->get_variation_attributes(false); // Get formatted variation attributes
update_post_meta($product_id, '_default_attributes', $default_attributes);
}
}
错误的 Woocommerce 默认变体
woocommerce_before_variations_form
太晚了,当时页面已经渲染了。尝试使用 template_redirect
或 wp
挂钩。