Override function

时间:2016-01-29 作者:Corentin Branquet

在woocommerce插件文件中class-wc-booking-cart-manager.php 有这个代码

/**
     * 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;
    }
我想换衣服add_cart_item 函数的代码进入我的子主题functions.php 文件我想知道如何重写这个插件函数。

所以我这样做了:

remove_all_filters(\'woocommerce_add_cart_item\');
add_filter(\'woocommerce_add_cart_item\', \'custom_add_cart_item\');

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;
}
如你所见,我把价格定在2000英镑。

但它不起作用。。谢谢你的帮助!

2 个回复
SO网友:Vasim Shaikh

下面是覆盖购物车中产品价格的代码

add_action( \'woocommerce_before_calculate_totals\', \'add_custom_price\' );

function add_custom_price( $cart_object ) {
    $custom_price = 10; // This will be your custome price  
    foreach ( $cart_object->cart_contents as $key => $value ) {
        $value[\'data\']->price = $custom_price;
    }
}

SO网友:AddWeb Solution Pvt Ltd

您正在使用woocommerce_add_cart_item, 请使用woocommerce_before_calculate_totals.

add_action( \'woocommerce_before_calculate_totals\', \'custom_add_cart_item\' );

function custom_add_cart_item( $cart_object ) {
    foreach ( $cart_object->cart_contents as $key => $value ) {
        if ( empty( $value[\'booking\'] ) && empty( $value[\'booking\'][\'_cost\'] ) {
            $value[\'data\']->price = 2000;
        }
    }
}
确保此代码始终是可执行的。添加此代码后。

相关推荐