Get the min or max variation ID in WooCommerce

if ( ! function_exists( 'wpcodebook_get_variation_id' ) ) {
    /**
     * Get the min or max (by price) active variation ID in WooCommerce.
     */
    function wpcodebook_get_variation_id( $variable_product_id, $min_or_max = 'min' ) {
        $product = wc_get_product( $variable_product_id );
        if ( $product && $product->is_type( 'variable' ) ) {
            $prices        = $product->get_variation_prices( true );
            $variation_ids = array_keys( $prices['price'] );
            return ( 'min' === $min_or_max ? $variation_ids[0] : $variation_ids[ count( $variation_ids ) - 1 ] );
        }
        return false; // not a (variable) product
    }
}

Leave a Comment