Override Woocommerce public function

2019-09-19 13:26发布

I want to override this function from class-product-addon-cart.php to my child theme functions.php:

/**
     * add_cart_item function.
     *
     * @access public
     * @param mixed $cart_item
     * @return void
     */
    public function add_cart_item( $cart_item ) {
        // Adjust price if addons are set
        if ( ! empty( $cart_item['addons'] ) && apply_filters( 'woocommerce_product_addons_adjust_price', true, $cart_item ) ) {

            $extra_cost = 0;

            foreach ( $cart_item['addons'] as $addon ) {
                if ( $addon['price'] > 0 ) {
                    $extra_cost += $addon['price'];
                }
            }

            $cart_item['data']->adjust_price( $extra_cost );
        }

        return $cart_item;
    }

I have a type of products called accomodation product from Woocommerce booking plugin Here's the code from booking class :

/**
 * Class for the booking product type
 */
class WC_Product_Booking extends WC_Product {
    private $availability_rules = array();

    /**
     * Constructor
     */
    public function __construct( $product ) {
        if ( empty ( $this->product_type ) ) {
            $this->product_type = 'booking';
        }

        parent::__construct( $product );
    }

So if this product is an accomodation product then execute the function.

I wrote this code but it does not work :

$accomodation = new WC_Product_Booking( get_the_ID() );
$product = new WC_Product( get_the_ID() );

if ($accomodation) {
    add_filter('woocommerce_product_addons_adjust_price', '__return_false');
} elseif($product) {
    add_filter('woocommerce_product_addons_adjust_price', true);
}

Thanks for your help !

1条回答
甜甜的少女心
2楼-- · 2019-09-19 14:15
add_filter('woocommerce_product_addons_adjust_price', 'rei_product_addons_adjust_price', 10, 2);    
function rei_product_addons_adjust_price($is_adjust,$cart_item ){
    $product = $cart_item['data'];

    if ($product->is_type('booking')) {
        $is_adjust = false;
    }

    return $is_adjust;

}
查看更多
登录 后发表回答