如何编辑单独销售的产品的添加到购物车验证消息

时间:2017-01-08 20:14:53

标签: wordpress function woocommerce

来自 class-wc-cart.php 的woocommerce插件文件的代码:

// Force quantity to 1 if sold individually and check for existing item in cart

            if ( $product_data->is_sold_individually() ) {
                $quantity         = apply_filters( 'woocommerce_add_to_cart_sold_individually_quantity', 1, $quantity, $product_id, $variation_id, $cart_item_data );
                $in_cart_quantity = $cart_item_key ? $this->cart_contents[ $cart_item_key ]['quantity'] : 0;

                if ( $in_cart_quantity > 0 ) {
                    throw new Exception( sprintf( '<a href="%s" class="button wc-forward">%s</a> %s', wc_get_cart_url(), __( 'View Cart', 'woocommerce' ), sprintf( __( 'You cannot add another &quot;%s&quot; to your cart.', 'woocommerce' ), $product_data->get_title() ) ) );
                }
            }

我想做的修改是改变

wc_get_cart_url()

wc_get_checkout_url()

并将修改后的代码添加到functions.php中,以便更改成为永久更改。但是如何实现这个??

1 个答案:

答案 0 :(得分:1)

如果您在WooCommerce之前运行自己的验证,则可以检查sold_individually()限制并显示您自己的错误通知,如下所示:

add_filter( 'woocommerce_add_to_cart_validation', 

'so_41537378_individual_validation', 5, 6 );
function so_41537378_individual_validation( $passed_validation, $product_id, $quantity, $variation_id = '', $variation = array(), $cart_item_data = array() ) {
    $product_data = wc_get_product( $product_id );

    // Load cart item data - may be added by other plugins
    $cart_item_data = (array) apply_filters( 'woocommerce_add_cart_item_data', $cart_item_data, $product_id, $variation_id );

    // Generate a ID based on product ID, variation ID, variation data, and other cart item data
    $cart_id        = WC()->cart->generate_cart_id( $product_id, $variation_id, $variation, $cart_item_data );

    // Find the cart item key in the existing cart
    $cart_item_key  = WC()->cart->find_product_in_cart( $cart_id );

    // Force quantity to 1 if sold individually and check for existing item in cart
    if ( $product_data->is_sold_individually() ) {
        $quantity         = apply_filters( 'woocommerce_add_to_cart_sold_individually_quantity', 1, $quantity, $product_id, $variation_id, $cart_item_data );
        $in_cart_quantity = $cart_item_key ? WC()->cart->cart_contents[ $cart_item_key ]['quantity'] : 0;

        if ( $in_cart_quantity > 0 ) {
            /* translators: %s: product name */
            $error_message = sprintf( '<a href="%s" class="button wc-forward">%s</a> %s', wc_get_checkout_url(), __( 'Checkout', 'your-plugin-textdomain' ), sprintf( __( 'You cannot add another "%s" to your cart.', 'your-plugin-textdomain' ), $product_data->get_title() ) );
            // add your notice
            wc_add_notice( $error_message, 'error' );
            $passed_validation = false;
        }
    }
    return $passed_validation;
}

编辑了很多错误,例如$this脱离上下文,未定义的变量等。经过测试和工作。