我写下面的功能为设置默认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默认变体
1条答案
按热度按时间wtlkbnrh1#
woocommerce_before_variations_form
太晚了,页面已经在那个时候呈现了。尝试template_redirect
或wp
钩子。