Override woocommerce wc-class function

admin2025-06-05  2

I'm not good in WP and plugins and will need some help here. I've read that is possible to alter some WC core function with filters and action but probably I didn't understand this correctly. I want to simply delete the shipping price from my cart page Total price field.

The function which is in woocommerce/includes/class-wc-cart-totals.php is:

protected function calculate_totals() {
    $this->set_total( 'total', round( $this->get_total( 'items_total', true ) + $this->get_total( 'fees_total', true ) + $this->get_total( 'shipping_total', true ) + array_sum( $this->get_merged_taxes( true ) ), 0 ) );
    $this->cart->set_total_tax( array_sum( $this->get_merged_taxes( false ) ) );

    // Allow plugins to hook and alter totals before final total is calculated.
    if ( has_action( 'woocommerce_calculate_totals' ) ) {
        do_action( 'woocommerce_calculate_totals', $this->cart );
    }

    // Allow plugins to filter the grand total, and sum the cart totals in case of modifications.
    $this->cart->set_total( max( 0, apply_filters( 'woocommerce_calculated_total', $this->get_total( 'total' ), $this->cart ) ) );
}

I've tried to copy it to my child theme function.php file like this:

add_action('calculate_totals', 'my_calculate_totals');

function my_calculate_totals() 
{
        $this->set_total( 'total', round( $this->get_total( 'items_total', true ) + $this->get_total( 'fees_total', true ) + array_sum( $this->get_merged_taxes( true ) ), 0 ) );
        $this->cart->set_total_tax( array_sum( $this->get_merged_taxes( false ) ) );

        // Allow plugins to hook and alter totals before final total is calculated.
        if ( has_action( 'woocommerce_calculate_totals' ) ) {
            do_action( 'woocommerce_calculate_totals', $this->cart );
        }

        // Allow plugins to filter the grand total, and sum the cart totals in case of modifications.
        $this->cart->set_total( max( 0, apply_filters( 'woocommerce_calculated_total', $this->get_total( 'total' ), $this->cart ) ) );
}

It doesn't work. Is this possible?

My goal is to just remove this from first line

$this->get_total( 'shipping_total', true )

UPDATE:

I have tried like this

add_action( 'woocommerce_calculate_totals', 'my_calculate_totals');

function my_calculate_totals($cart = null) 
{
        $cart = new WC_Cart_Totals();
        $this->set_total( 'total', round( $this->get_total( 'items_total', true ) + $this->get_total( 'fees_total', true ) + array_sum( $this->get_merged_taxes( true ) ), 0 ) );
        $this->cart->set_total_tax( array_sum( $this->get_merged_taxes( false ) ) );

}

Got this error

A valid WC_Cart object is required

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749112232a316463.html

最新回复(0)