UWooCommerce – add cart discount programmatically?

I need to develop a plugin that applies a discount to the cart if x number of products have been purchased. Could someone point me in the direction of the code/API I need to use.

Can find nothing from https://docs.woothemes.com/documentation/plugins/woocommerce/woocommerce-codex/ and do not fancy paying $100+ for the official bulk discount plugin just to get some simple functionality like this.

I have found that WooCommerce’s get_total_discount() function applies the woocommerce_cart_total_discount filter, but I don’t seem to be able to successfully tap into that filter…

function mwe_calculate_discount( $total_discount, $cart ) {

    //global $woocommerce;
    $num_products_required_for_discount = 4;

    echo "<!-- Discount? -->";

    $number_products = $cart->cart_contents_count;
    if ($number_products >= $num_products_required_for_discount) {

        echo "<!-- QUALIFIES FOR DISCOUNT! -->";

        for ($i = 0; $i < $number_products; $i++) {

            // Get the reduced price of the product - TODO

            // Calculate $product_discount
            $product_discount = 11.11; // TODO

            // Add $product_discount to the $total_discount
            $total_discount += $product_discount;

        echo "<!-- Total discount: $total_discount -->";

    else {

        echo "<!-- NO DISCOUNT -->";


    return $total_discount;

add_filter('woocommerce_cart_total_discount', 'mwe_calculate_discount', 10, 2);

…any idea what is wrong with my code?

Solutions Collecting From Web of "UWooCommerce – add cart discount programmatically?"