在Woocommerce购物车对象中添加自定义字段选定的变体值

问题描述 投票:1回答:2

在WooCommerce我使用变量产品,其变化基于日期可用性。

在后端,我已经在变量产品设置的每个变体上成功添加了2个自定义价格(成人/儿童)的自定义字段(2个自定义字段显示在底部):

Screen shot of Back-end variations: The 2 custom fields at the bottom

2个价格必须显示在相同的变量上,因为它们与相同的日期属性和数量相关联。

问题 我可以在后端定义价格,在前端显示数量选择器,但我无法在添加到购物车按钮的同一“点击”中将它们添加到购物车。当用户点击添加到购物车按钮时,适当数量的成人被添加到购物车中,数量合适,但我不知道如何添加儿童...

事实上,我还想在购物车中添加与同一变体相对应的另一个项目,但子项价格和数量,以及“价格:儿童”等属性。

我正在考虑使用add_to_cart函数,例如:

add_to_cart( $product_id , $quantity , $variation_id, $variation , array(__('Price:','ah')=>__('Children','ah)) );

使用适当的$product_id$variation_id$variation$quantity =孩子输入的数量,但我真的不知道在何时何地勾选以适当地包括。

我尝试过(但不起作用):

  • 我已经尝试连接到add_to_cart本身,但只是成功创建了一个以错误结束的递归调用。
  • 我也试图加入woocommerce_before_calculate_totals,但它似乎是改变价格的正确位置,但是添加新产品并为其设定数量“为时已晚”。

显示成人和儿童的数量和价格 产品页面被修改为显示2个价格,每个价格选择器,以及动态计算总数的jQuery脚本:

前端视图,价格和数量选择器,以及总View of the front-end, with prices and quantity selector, and automatic calculation of total的自动计算

这是我的代码:

function ah_activity_product_price_display() {
    global $product;
    $stock = $product->get_total_stock();
    $pricepolicy = get_post_meta( $product->id, '_ah_pricing', true );
    if( is_activity()) {
        $price_list = array();
        if ($pricepolicy == 'multiple') { 
            $variations=$product->get_available_variations();
            foreach ($variations as $variation) {
                $variation_id = $variation['variation_id'] ;
                $start = $variation['attributes']['attribute_date'];
                $price_list[$start]['adult_price'] = get_post_meta( $variation_id, '_adult_price', true );
                $price_list[$start]['children_price'] = get_post_meta( $variation_id, '_children_price', true );
            }
            //var_dump($price_list,json_encode($price_list));
            ?>
            <div class="multiple">
                <p class="clear">
                    <div class="quantity">
                        <input class="minus" type="button" value="-">
                        <input type="number" step="1" min="1" max="<?php echo esc_attr( 0 < $stock ? $stock : '' ); ?>" name="nb_adulte" value="1" title="<?php echo esc_attr_x( 'Adult number', 'Product quantity input tooltip', 'ah' ); ?>" class="input-text qty text" size="4" pattern="" inputmode="" />
                        <input class="plus" type="button" value="+">
                    </div> <?php _e('Adult x ','ah'); ?> <span class="prix-adulte"><?php esc_html($adult_price); ?></span> €
                </p>
                <p class="clear">
                    <div class="quantity">
                        <input class="minus" type="button" value="-">
                        <input type="number" step="1" min="0" max="<?php echo esc_attr( 0 < $stock ? $stock : '' ); ?>" name="nb_enfant" value="0" title="<?php echo esc_attr_x( 'Children number', 'Product quantity input tooltip', 'ah' ); ?>" class="input-text qty text" size="4" pattern="" inputmode="" />
                        <input class="plus" type="button" value="+">
                    </div> <?php _e('Children (under 18) x ','ah'); ?> <span class="prix-enfant"><?php echo esc_html($children_price); ?></span> €
                </p>
            </div>
            <?php 
        }
        echo '<input type="hidden" id="pricelist" name="pricelist" value=\''.json_encode($price_list).'\'>';

    } else {
        woocommerce_get_price_html();
    }

}   
php wordpress woocommerce product variations
2个回答
2
投票

我几乎成功地实现了我想要的东西。这是PHP中添加的代码:

/**
 * Définition et paramètres des scripts pour ajout au panier
 */
add_action( 'wp_enqueue_scripts', 'ah_load_script', 20 );
function ah_load_script(){
    wp_enqueue_script( 'ah_ajax_add_to_cart', get_stylesheet_directory_uri() . '/js/test.js' );
    $i18n = array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'checkout_url' => get_permalink( wc_get_page_id( 'checkout' ) ) );
    wp_localize_script( 'ah_ajax_add_to_cart', 'ah_add_to_cart_params', $i18n );
}
/**
 * Fonction d'ajout au panier Ajax
 */
add_action('wp_ajax_myajax', 'ah_add_to_cart_callback');
add_action('wp_ajax_nopriv_myajax', 'ah_add_to_cart_callback');

    /**
     * AJAX add to cart.
     */
function ah_add_to_cart_callback() {        
    ob_start();
    //$product_id        = 264;
    $product_id        = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $_POST['product_id'] ) );
    $quantity          = empty( $_POST['quantity'] ) ? 1 : wc_stock_amount( $_POST['quantity'] );
    $variation_id      = isset( $_POST['variation_id'] ) ? absint( $_POST['variation_id'] ) : '';
    $variations         = ! empty( $_POST['variation'] ) ? (array) $_POST['variation'] : '';

    $passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity, $variation_id, $variations, $cart_item_data );
    $product_status    = get_post_status( $product_id );
    if ( $passed_validation && WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variations ) && 'publish' === $product_status ) {
        do_action( 'woocommerce_ajax_added_to_cart', $product_id );
        wc_add_to_cart_message( $product_id );
    } else {
        // If there was an error adding to the cart, redirect to the product page to show any errors
        $data = array(
            'error'       => true,
            'product_url' => apply_filters( 'woocommerce_cart_redirect_after_error', get_permalink( $product_id ), $product_id )
        );
        wp_send_json( $data );
    }
    die();
}

这是相应的js(对不起,如果代码很丑,但我不是一个真正的js编码器,只是一个自学...):

jQuery(document).ready(function($){

  $(".test-button").click(function(e){ 
    e.preventDefault();  // Prevent the click from going to the link
    $variation_form = $( this ).closest( '.variations_form' );
    var product_id = $variation_form.find( 'input[name=product_id]' ).val();
    var adult_qty = $variation_form.find( 'input[name=nb_adulte]' ).val();
    var children_qty = $variation_form.find( 'input[name=nb_enfant]' ).val();
    var adult_price = $variation_form.find( '.prix-adulte' ).text();
    var children_price = $variation_form.find( '.prix-enfant' ).text();

    var var_id = $variation_form.find( 'input[name=variation_id]' ).val();
    var att_date = $variation_form.find( 'select[name=attribute_date]' ).val();
    var att_adult = "adulte";
    var att_children = "enfant";

    $.ajax({
        url: ah_add_to_cart_params.ajax_url,
        method: 'post',
        data: {
            'action': 'myajax',
            'product_id': product_id,
            'quantity': adult_qty,
            'price' : adult_price,
            'variation_id': var_id,
            'variation': { 'attribute_date': att_date, 'attribute_tarif': att_adult }
        }
    }).done( function (response) {
      if( response.error != 'undefined' && response.error ){
        //some kind of error processing or just redirect to link
        // might be a good idea to link to the single product page in case JS is disabled
        return true;
      } else {
        $.ajax({
            url: ah_add_to_cart_params.ajax_url,
            method: 'post',
            data: {
                'action': 'myajax',
                'product_id': product_id,
                'quantity': children_qty,
                'price' : children_price,
                'variation_id': var_id,
                'variation': { 'attribute_date': att_date, 'attribute_tarif': att_children }
            }
        }).done( function (response) {
          if( response.error != 'undefined' && response.error ){
            //some kind of error processing or just redirect to link
            // might be a good idea to link to the single product page in case JS is disabled
            return true;
          } else {
            window.location.href = ah_add_to_cart_params.checkout_url;
          }
        });
      }
    });
  });
});

这增加了2个产品,属性“定价”=>“成人”或“儿童”,以及相应的数量,但价格是变化的默认价格(不是我的自定义价格),因为我不知道如何将它包含在WC()->cart->add_to_cart电话中(see how my cart looks with the above code for 5 adult, 2 children)。


0
投票

好的,一切都完成了!作为我以前的答案的补充,这里是我添加的一些代码,用于相应地设置成人/儿童价格的相应变化的价格,以防它可以帮助其他人:

/**
 * Override price in cart in case of adult/children prices
 */
function ah_add_custom_price( $cart_object ) {
    $custom_price = 10; // This will be your custom price  
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        //var_dump($cart_item);
        $my_item = $cart_item['variation'];
        $adult_price = get_post_meta($cart_item['variation_id'], "_adult_price" , true );
        $children_price = get_post_meta($cart_item['variation_id'], "_children_price" , true );
        if ( array_key_exists('attribute_tarif', $my_item) ) {
            if (( $my_item['attribute_tarif'] == "adulte" ) && ( isset($adult_price) ) ) {
                $cart_item['data']->set_price($adult_price);
            } elseif (( $my_item['attribute_tarif'] == "enfant" ) && ( isset($children_price) ) ) {
                $cart_item['data']->set_price($children_price);   
            }
        } 

    }
}
add_action( 'woocommerce_before_calculate_totals', 'ah_add_custom_price' );

这是结果:Product page with adult/children prices

Cart with custom attribute and custom price

© www.soinside.com 2019 - 2024. All rights reserved.