Corentin Branquet
Corentin Branquet

Reputation: 1576

How to rewrite functions wordpress

In woocommerce plugin file class-wc-booking-cart-manager.php there is this code

/**
     * Constructor
     */
    public function __construct() {
        add_filter( 'woocommerce_add_cart_item', array( $this, 'add_cart_item' ), 10, 1 );
        }

/**
     * Adjust the price of the booking product based on booking properties
     *
     * @param mixed $cart_item
     * @return array cart item
     */
    public function add_cart_item( $cart_item ) {
        if ( ! empty( $cart_item['booking'] ) && ! empty( $cart_item['booking']['_cost'] ) ) {
            $cart_item['data']->set_price( $cart_item['booking']['_cost'] );
        }
        return $cart_item;
    }

I want to change add_cart_item function's code into my child theme functions.php file

So I did this :

function custom_add_cart_item($cart_item) {
    if (empty( $cart_item['booking'] ) && empty( $cart_item['booking']['_cost'] ) ) {
        $cart_item['data']->set_price(2000);
    }
    return $cart_item;
}


function setup_add_cart_item_filter(){
    remove_filter( 'woocommerce_add_cart_item', array('WC_Booking_Cart_Manager', 'add_cart_item' ), 10, 1 );
    add_filter('woocommerce_add_cart_item', 'custom_add_cart_item');
}

add_action( 'after_setup_theme', 'setup_add_cart_item_filter' );

But it does not work. Thanks for your help !

Upvotes: 1

Views: 506

Answers (1)

slbteam08
slbteam08

Reputation: 681

You may call remove_all_filters('woocommerce_add_cart_item'); to remove existing hook, then call add_filter( 'woocommerce_add_cart_item', 'your_new_add_cart_item' ); in functions.php

EDIT: I missed a point that childtheme's functions.php is loaded before parent theme's, so running remove_all_filters() directly in functions.php is actually useless...

My updated answer is to wrap those calls in another function and call them after theme setup phrase:

function setup_add_cart_item_filter(){
    remove_all_filters('woocommerce_add_cart_item');
    add_filter('woocommerce_add_cart_item', 'custom_add_cart_item');
}
add_action( 'after_setup_theme', 'setup_add_cart_item_filter' );

Upvotes: 1

Related Questions